Search code examples
c++eigen3

Save the matrix in array format after calling matrix.array()


I switched from matlab to C++ to write a CFD solver. I am using Eigen linear algebra library. It has many function for the Matrix and Vector manipulations but it's lacking in functions to convert Matrix to Array.

 MatrixXf m(2,2);
 m<<1,2,3,4;
 ArrayXf a(4);
 a=m.array();

This is the solution I have for this

 m.resize(4,1);
 a=m;

I don' like this because the m is changed, which I don't want because m is a very big matrix.


Solution

  • If you don't want to copy the values you can use an Eigen::Map like so:

    MatrixXf m(2,2);
    m<<1,2,3,4;
    Eigen::Map<ArrayXf> mp(m.data(), m.size());
    

    You can then use mp as an ArrayXf. Note that this points to the original m matrix, i.e. changes to mp will be present in m. If you want a copy, you can use:

    ArrayXf a = mp;