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.

Dani AI

Generated

For : a simple, idiomatic way in C++ is to append each time-step vector as a column in a container rather than trying to grow a raw 2D C array inside the loop. Two practical patterns follow — pick the one that fits plotting and performance needs.

A readable approach: store columns as a vector of vectors. This keeps each column as a self-contained vector and makes appending trivial.

// each iteration produces a vector<double> nums of length `rows`
std::vector<std::vector<double>> cols;
cols.reserve(expectedSteps); // optional

for (int t = 0; t < steps; ++t) {
    std::vector<double> nums = compute_values_for_time(t);
    cols.push_back(std::move(nums)); // move avoids a second copy
}

// element at (row r, column c):
double val = cols[c][r];

If memory locality and fewer allocations matter (faster plotting or large data), store the matrix in one flat vector in column-major order:

std::vector<double> mat;
mat.reserve(rows * expectedSteps);

for (int t = 0; t < steps; ++t) {
    for (size_t r = 0; r < rows; ++r)
        mat.push_back(nums[r]); // append column values
}

// access (r,c):
double val = mat[c * rows + r];

Notes and tips: prefer reserve to reduce reallocations; use std::move when reusing the same temporary vector to avoid copies; pick the column-major flat layout if code will repeatedly read whole columns (better cache behavior). This avoids the repeated reallocation approach mentioned by and is simpler and safer than manual C arrays like the snippet from . If matrix math or conveniences are needed, consider a matrix library (Eigen/Armadillo) which supports growing columns via conservative resize and column assignment.

Recommended Answers

All 2 Replies

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
        }
 }

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.