Eenoku
Eenoku

Reputation: 2977

Armadillo and C++ - Matrix initialization with 2D-array

I need to initialize Armadillo matrix with the array of doubles. I've found this constructor in the original documentation:

mat(*aux_mem, n_rows, n_cols, copy_aux_mem = true, strict = true) 

and I've found the question about it here on SO:

armadillo C++: matrix initialization from array

The problem is, it appears that the constructor works only for initialization with one-dimensional arrays, not 2D. If I try it to use this way:

double **matrix = new double *[block_size];
for(int i = 0; i < block_size; i++) {
    matrix[i] = new double[block_size];
}

arma::mat arma_matrix( &matrix[0][0], matrix_size, matrix_size, true, true );

cout << "am: " << arma_matrix[1][0] << endl;

I get the error:

fined_grain:103/init_function: In function ‘void place_user_fn_103(ca::Context&, ca::TokenList<double>&)’:
fined_grain:103/init_function:61:42: error: invalid types ‘double[int]’ for array subscript

So, what's the ideal way to initialize Arma matrix with 2D-array? I prefer the fastest solution, because I need to use big matrices.

Upvotes: 1

Views: 3356

Answers (1)

R Sahu
R Sahu

Reputation: 206577

I took a quick glance at the armadillo library documentation and I see the following problems.

  1. The argument you are passing to arma_matrix is syntactically right but incorrect. You need to use:

    double *matrix = new double [block_size*block_size];
    arma::mat arma_matrix( matrix, block_size, block_size, true, true );
    
  2. The syntax for accessing the elements is:

    cout << "am: " << arma_matrix(1, 0) << endl;
    

    You can also use:

    int row = 1;
    int col = 0;
    cout << "am: " << arma_matrix[row*block_size+col] << endl;
    

Upvotes: 1

Related Questions