分享

Map a Eigen Matrix to an C array

 imelee 2017-09-27

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;
asked Nov 23 '12 at 20:33
Jack Lei
543518

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;

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多