1

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.

Community
  • 1
  • 1
Eenoku
  • 2,741
  • 4
  • 32
  • 64
  • @user3670482 - in my experience, the Boost matrix library is quite primitive compared to Armadillo – mtall Mar 04 '15 at 02:48
  • @user3670482 Unfortunately, I have to use Armadillo. Still, thank you for your advice ;-) – Eenoku Mar 04 '15 at 08:37
  • @mtall Have you tried exploiting Boost matrix with C++11 patterns? You might be able to do lots of cool things with that. – The Vivandiere Mar 04 '15 at 11:43
  • By the way, Martin, the guidelines for Modern C++ say that you should not use owning pointers, I.e. No new and delete. If you must use a pointer to deference the matrices, I'd say use a smart pointer like unique_ptr – The Vivandiere Mar 04 '15 at 11:46

1 Answers1

1

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;
    
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • To avoid copying the memory, change `arma::mat arma_matrix( matrix, block_size, block_size, true, true )` to `arma::mat arma_matrix( matrix, block_size, block_size, false, true )`, ie. the 4th arg is changed to `false`. This is faster, but see the caveats described in the [associated documentation notes](http://arma.sourceforge.net/docs.html#adv_constructors_mat) (eg. because you're now using the memory directly, you'll now be responsible for memory deallocation, handling aliasing, etc). – mtall Mar 04 '15 at 02:47