Mapping array back to an existing Eigen matrix

Manolete picture Manolete · Aug 17, 2012 · Viewed 15.1k times · Source

I want to map an array of double to an existing MatrixXd structure. So far I've managed to map the Eigen matrix to a simple array, but I can't find the way to do it back.

void foo(MatrixXd matrix, int n){

 double arrayd = new double[n*n];
 // map the input matrix to an array
 Map<MatrixXd>(arrayd, n, n) = matrix;  

  //do something with the array 
             .......
// map array back to the existing matrix

}

Answer

Jitse Niesen picture Jitse Niesen · Aug 17, 2012

I'm not sure what you want, but I'll try to explain.

You're mixing double and float in your code (a MatrixXf is a matrix where every entry is a float). I'll assume for the moment that this was unintentional amd that you want to use double everywhere; see below for if this was really your intention.

The instruction Map<MatrixXd>(arrayd, n, n) = matrix copies the entries of matrix into arrayd. It is equivalent to the loop

for (int i = 0; i < n; ++i)
   for (int j = 0; j < n; ++j)
      arrayd[i + j*n] = matrix(i, j);

To copy the entries of arrayd into matrix, you would use the inverse assignment: matrix = Map<MatrixXd>(arrayd, n, n).

However, usually the following technique is more useful:

void foo(MatrixXd matrix, int n) {
   double* arrayd = matrix.data();
   // do something with the array 
}

Now arrayd points to the entries in the matrix and you can process it as any C++ array. The data is shared between matrix and arrayd, so you do not have to copy anything back at the end. Incidentally, you do not need to pass n to the function foo(), because it is stored in the matrix; use matrix.rows() and matrix.cols() to query its value.

If you do want to copy a MatrixXf to an array of doubles, then you need to include the cast explicitly. The syntax in Eigen for this is: Map<MatrixXd>(arrayd, n, n) = matrix.cast<double>() .