Map a Eigen Matrix to an C array

2019-03-27 18:12发布

I recently started to use the Eigen library. I got a question of mapping an Eigen matrix to a C/C++ array. An Eigen matrix is column majored by default. So if i use the following code to map a matrix to an C/C++ array,

double a[10];
double *p = &a[0];
MatrixXd(2,5) m;
for (int i=0; i<2;i++)
    for (int j=0; j<5;j++)
        m(i,j) = i+j;
cout<<m<<endl;
Eigen::Map<MatrixXd>(p,2,5) = m;
for (int i=0; i<10; i++)
    cout<<a[i]<<" ";
cout<<endl;

The output is:

0 1 2 3 4
1 2 3 4 5
0 1 1 2 2 3 3 4 4 5

If I change the the definition of m as row majored:

Matrix <double,2,5,RowMajor> m;

i expected the output looks like this:

0 1 2 3 4
1 2 3 4 5
0 1 2 3 4 1 2 3 4 5

But actually the result was still the same as the first one. My question is that is there a way to map an Eigen matrix to an C/C++ array so that the data of the array is row based?

I found that I can use the matrix.data() memember function to get the desired result, but I'm wondering whether I can do this use map:

Use matrix.data() works:

double a[10];
double *p = &a[0];
Matrix <double,2,5,RowMajor> m;
for (int i=0; i<2;i++)
    for (int j=0; j<5;j++)
        m(i,j) = i+j;
double *p1 = m.data();
for (int i=0; i<10; i++)
    cout<<p1[i]<<" ";
cout<<endl;

1条回答
Ridiculous、
2楼-- · 2019-03-27 18:20

It's not the type of the matrix m that matters, but the type used in the Map template. You have to change the type used in the Map template to be row major.

Eigen::Map<Matrix<double,2,5,RowMajor> >(p,2,5) = m;
查看更多
登录 后发表回答