Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Eigen Matrix to C array

The Eigen library can map existing memory into Eigen matrices.

float array[3]; Map<Vector3f>(array, 3).fill(10); int data[4] = 1, 2, 3, 4; Matrix2i mat2x2(data); MatrixXi mat2x2 = Map<Matrix2i>(data); MatrixXi mat2x2 = Map<MatrixXi>(data, 2, 2); 

My question is, how can we get c array (e.g. float[] a) from eigen matrix (e.g. Matrix3f m)? What it the real layout of eigen matrix? Is the real data stored as in normal c array?

like image 201
lil Avatar asked Dec 09 '11 08:12

lil


2 Answers

You can use the data() member function of the Eigen Matrix class. The layout by default is column-major, not row-major as a multidimensional C array (the layout can be chosen when creating a Matrix object). For sparse matrices the preceding sentence obviously doesn't apply.

Example:

ArrayXf v = ArrayXf::LinSpaced(11, 0.f, 10.f); // vc is the corresponding C array. Here's how you can use it yourself: float *vc = v.data(); cout << vc[3] << endl;  // 3.0 // Or you can give it to some C api call that takes a C array: some_c_api_call(vc, v.size()); // Be careful not to use this pointer after v goes out of scope! If // you still need the data after this point, you must copy vc. This can // be done using in the usual C manner, or with Eigen's Map<> class. 
like image 65
janneb Avatar answered Oct 22 '22 19:10

janneb


To convert normal data type to eigen matrix type

  double *X; // non-NULL pointer to some data 

You can create an nRows x nCols size double matrix using the Map functionality like this:

  MatrixXd eigenX = Map<MatrixXd>( X, nRows, nCols ); 

To convert eigen matrix type into normal data type

  MatrixXd resultEigen;   // Eigen matrix with some result (non NULL!)   double *resultC;        // NULL pointer <-- WRONG INFO from the site. resultC must be preallocated!   Map<MatrixXd>( resultC, resultEigen.rows(), resultEigen.cols() ) =   resultEigen; 

In this way you can get in and out from eigen matrix. Full credits goes to http://dovgalecs.com/blog/eigen-how-to-get-in-and-out-data-from-eigen-matrix/

like image 44
GPrathap Avatar answered Oct 22 '22 19:10

GPrathap