Eigen教程(8)


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

原生緩存的接口:Map類

這篇將解釋Eigen如何與原生raw C/C++ 數組混合編程。

簡介

Eigen中定義了一系列的vector和matrix,相比copy數據,更一般的方式是復用數據的內存,將它們轉變為Eigen類型。Map類很好地實現了這個功能。

Map類型

Map的定義

Map<Matrix<typename Scalar, int RowsAtCompileTime, int ColsAtCompileTime> >

默認情況下,Mao只需要一個模板參數。

為了構建Map變量,我們需要其余的兩個信息:一個指向元素數組的指針,Matrix/vector的尺寸。定義一個float類型的矩陣: Map<MatrixXf> mf(pf,rows,columns); pf是一個數組指針float *。

固定尺寸的整形vector聲明: Map<const Vector4i> mi(pi);

注意:Map沒有默認的構造函數,你需要傳遞一個指針來初始化對象。

Mat是靈活地足夠去容納多種不同的數據表示,其他的兩個模板參數:

Map<typename MatrixType,
    int MapOptions,
    typename StrideType>

MapOptions標識指針是否是對齊的(Aligned),默認是Unaligned。

StrideType表示內存數組的組織方式:行列的步長。

int array[8];
for(int i = 0; i < 8; ++i) array[i] = i;
cout << "Column-major:\n" << Map<Matrix<int,2,4> >(array) << endl;
cout << "Row-major:\n" << Map<Matrix<int,2,4,RowMajor> >(array) << endl;
cout << "Row-major using stride:\n" <<
  Map<Matrix<int,2,4>, Unaligned, Stride<1,4> >(array) << endl;

輸出

Column-major:
0 2 4 6
1 3 5 7
Row-major:
0 1 2 3
4 5 6 7
Row-major using stride:
0 1 2 3
4 5 6 7

使用Map變量

可以像Eigen的其他類型一樣來使用Map類型。

typedef Matrix<float,1,Dynamic> MatrixType;
typedef Map<MatrixType> MapType;
typedef Map<const MatrixType> MapTypeConst;   // a read-only map
const int n_dims = 5;
  
MatrixType m1(n_dims), m2(n_dims);
m1.setRandom();
m2.setRandom();
float *p = &m2(0);  // get the address storing the data for m2
MapType m2map(p,m2.size());   // m2map shares data with m2
MapTypeConst m2mapconst(p,m2.size());  // a read-only accessor for m2
cout << "m1: " << m1 << endl;
cout << "m2: " << m2 << endl;
cout << "Squared euclidean distance: " << (m1-m2).squaredNorm() << endl;
cout << "Squared euclidean distance, using map: " <<
  (m1-m2map).squaredNorm() << endl;
m2map(3) = 7;   // this will change m2, since they share the same array
cout << "Updated m2: " << m2 << endl;
cout << "m2 coefficient 2, constant accessor: " << m2mapconst(2) << endl;
/* m2mapconst(2) = 5; */   // this yields a compile-time error

輸出

m1:   0.68 -0.211  0.566  0.597  0.823
m2: -0.605  -0.33  0.536 -0.444  0.108
Squared euclidean distance: 3.26
Squared euclidean distance, using map: 3.26
Updated m2: -0.605  -0.33  0.536      7  0.108
m2 coefficient 2, constant accessor: 0.536

Eigen提供的函數都兼容Map對象。

改變mapped數組

Map對象聲明后,可以通過C++的placement new語法來改變Map的數組。

int data[] = {1,2,3,4,5,6,7,8,9};
Map<RowVectorXi> v(data,4);
cout << "The mapped vector v is: " << v << "\n";
new (&v) Map<RowVectorXi>(data+4,5);
cout << "Now v is: " << v << "\n";

The mapped vector v is: 1 2 3 4
Now v is: 5 6 7 8 9


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM