Hello everyone:

I am a C++ newbie. I have used Matlab to fill the rows or columns of a matrix with values from a vector and I'm wondering how to do the same thing in C++...

I have written code that puts new values in a vector. This happens in a "for" loop. Each iteration of the loop represents a new time. So for each time/loop, I have a new set of values in the vector that I need to store.

I would like to take the vector and store it as a column of a matrix outside the loop. Can anyone suggest how to do this? The reason I want to do this is that I want to plot the values from each vector over time. I think I could "return" the vector at the end of each loop and maybe save it, but I don't know how to make a matrix that grows during looping (has new columns added).

I would be grateful for any help or advice.

I do not know how to add new columns to a matrix either.

This may not be the exact answer you are looking for, but I think it is similar to what you want to do:

//if you had a vector called nums, and a 2d array called ary, you could do this:
//put nums from vector (or you could use an array) into 2d array
  for(int r = 0; r<ROWS; r++){
        for(int c = 0; c<COLS; c++){
                ary[r][0]= nums[r]; //for every row, the 1st column will be populated from the vector...no change to the other columns
        }
 }

Edited 6 Years Ago by MyrtleTurtle: spelling

option 1:
Each time you want to add a new column to the left hand side of the matrix declare a new, bigger matrix using dynamic memory, then load the data from the vector in the first column using a loop, followed by another loop transfer the data from old matrix (you could combine both loops together if you wish, too).

option 2:
Declare a really big matrix and add information at the first available column. Always read the matrix "backward", so the last entry acts like the first.

option 3:
I suspect there is a way to use a vector of vectors to do this somehow, too, but I can't come up with it right now. If new vectors added to the vector of vectors are added as the lowest row of the vector of vectors, then you could do a transpose of the data fom row major to column major starting from the lowest row instead of the top row like most matrix transpositions go or you could swap positions of the vectors so bottom row goes to top etc and then do a standard matrix transposition. Trouble is I'm not sure where new vectors are added when adding a new vector to a vector of vectors.

This article has been dead for over six months. Start a new discussion instead.