Eigen教程(9)

整理下Eigen库的教程,参考:http://eigen.tuxfamily.org/dox/index.html

Eigen并没有为matrix提供直接的Reshape和Slicing的API,但是这些特性可以通过Map类来实现。

Reshape

reshape操作是改变matrix的尺寸大小但保持元素不变。采用的方法是创建一个不同“视图” Map。

MatrixXf M1(3,3);    // Column-major storage
M1 << 1, 2, 3,
      4, 5, 6,
      7, 8, 9;
Map<RowVectorXf> v1(M1.data(), M1.size());
cout << "v1:" << endl << v1 << endl;
Matrix<float,Dynamic,Dynamic,RowMajor> M2(M1);
Map<RowVectorXf> v2(M2.data(), M2.size());
cout << "v2:" << endl << v2 << endl;

输出

v1:
1 4 7 2 5 8 3 6 9
v2:
1 2 3 4 5 6 7 8 9

reshape 2*6的矩阵到 6*2

MatrixXf M1(2,6);    // Column-major storage
M1 << 1, 2, 3,  4,  5,  6,
      7, 8, 9, 10, 11, 12;
Map<MatrixXf> M2(M1.data(), 6,2);
cout << "M2:" << endl << M2 << endl;

输出

M2:
 1  4
 7 10
 2  5
 8 11
 3  6
 9 12

Slicing

也是通过Map实现的,比如:每p个元素获取一个。

RowVectorXf v = RowVectorXf::LinSpaced(20,0,19);
cout << "Input:" << endl << v << endl;
Map<RowVectorXf,0,InnerStride<2> > v2(v.data(), v.size()/2);
cout << "Even:" << v2 << endl;

输出

Input:
 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19
Even: 0  2  4  6  8 10 12 14 16 18
posted @ 2017-01-25 20:49  侯凯  阅读(3344)  评论(0编辑  收藏  举报