Map a Eigen Matrix to an C array

非 Y 不嫁゛ 提交于 2019-12-12 08:00:40

问题


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:


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;


来源:https://stackoverflow.com/questions/13535399/map-a-eigen-matrix-to-an-c-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!