Mapping an array back to an existing native matrix

I want to map a double structure array to an existing MatrixXd structure. So far I have managed to map the Eigen matrix to a simple array, but I cannot find a way to do this.

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 } 
+6
source share
2 answers

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

You mix double and float in your code (MatrixXf is a matrix where each record is a float). At the moment, I assume that this was unintentional and that you want to use double everywhere; see below if this really was your intention.

The Map<MatrixXd>(arrayd, n, n) = matrix instruction Map<MatrixXd>(arrayd, n, n) = matrix copies matrix entries to arrayd . This is equivalent to a loop

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

To copy arrayd entries into matrix , you must use reverse assignment: matrix = Map<MatrixXd>(arrayd, n, n) .

However, the following method is usually 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 treat it like any C ++ array. Data is shared between matrix and arrayd , so you don't need to copy anything at the end. By the way, you do not need to pass n function foo() , because it is stored in the matrix; use matrix.rows () and matrix.cols () to request its value.

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

+13
source

You do not need to perform the reverse operation.

When using Eigen :: Map, you map the raw array to the Eigen class. This means that you can now read or write using the Eighen functions.

If the associated array changes, the changes already exist. You can just access the original array.

 float buffer[16]; //a raw array of float //let map the array using an Eigen matrix Eigen::Map<Eigen::Matrix4f> eigenMatrix(buffer); //do something on the matrix eigenMatrix = Eigen::Matrix4f::Identity(); //now buffer will contain the following values //buffer = [1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1] 
+8
source

Source: https://habr.com/ru/post/923106/


All Articles