Search code examples
c++armadillo

How to use a for loop to add elements to a vec or a rowvec?


Trying to use a for loop to add elements in a vec or a rowvec, but each time the loop adds an element, the matrix resets each time?

Noob in Armadillo, I've looked at the documentation but I can't even find a single sample example where they use for loops. Thanks for any help.

arma::vec A;
for (int i = 0; i < 10; i++) {
    A << i;
}
cout << A;

Expected output : 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0

Actual output : 9.0


Solution

  • There are several approaches to accomplish this. The first approach is to simply declare the size of the vector beforehand and set the individual elements:

    arma::vec A(10);
    for (arma::uword i = 0; i < 10; ++i) {
        A(i) = i;
    }
    

    If you don't know how many elements you need beforehand, follow the other approaches detailed in the answers to: push_back/append or appending a vector with a loop in C++ Armadillo