Search code examples
armadillo

Armadillo - initialize a matrix and fill matrix with values


I would like to fill a matrix column wise. I have the following numpy code which I am having difficulty converting to C++ Armadillo.

# numpy code
m = np.zeros((nrows, nrows))
# fill a matrix of lags
for i in range(0, nrows):
    r = np.roll(vec_v, i)
    m[:, i] = r

where vec_v is a single column vector and nrows is the number of rows in that column vector.

This is my Armadillo attempt

# armadillo conversion
mat m(nrows, nrows); m.zeroes();

for(int i = 0; i < nrows; i++){
  vec r = shift(vec_v, i)
  m.col(i).fill(r);
}

What is the reccommended way to initialize a matrix then fill the values column-wise.


Solution

  • The = operator should work here.

    mat m(nrows, nrows); m.zeros();
    
    for(int i = 0; i < nrows; i++){
      vec r = shift(vec_v, i);
      m.col(i) = r;
    }
    

    Matrix initialization can be simplified and the generation of the temporary r vector can be avoided, as below.

    mat m(nrows, nrows, fill::zeros);
    
    for(int i = 0; i < nrows; i++){
      m.col(i) = shift(vec_v, i);
    }