Eigen教程(8)
整理下Eigen庫的教程,參考:http://eigen.tuxfamily.org/dox/index.html
原生緩存的接口:Map類
這篇將解釋Eigen如何與原生raw C/C++ 數(shù)組混合編程。
簡介
Eigen中定義了一系列的vector和matrix,相比copy數(shù)據(jù),更一般的方式是復用數(shù)據(jù)的內存,將它們轉變?yōu)镋igen類型。Map類很好地實現(xiàn)了這個功能。
Map類型
Map的定義
Map<Matrix<typename Scalar, int RowsAtCompileTime, int ColsAtCompileTime> >默認情況下,Mao只需要一個模板參數(shù)。
為了構建Map變量,我們需要其余的兩個信息:一個指向元素數(shù)組的指針,Matrix/vector的尺寸。定義一個float類型的矩陣: Map<MatrixXf> mf(pf,rows,columns); pf是一個數(shù)組指針float *。
固定尺寸的整形vector聲明: Map<const Vector4i> mi(pi);
注意:Map沒有默認的構造函數(shù),你需要傳遞一個指針來初始化對象。
Mat是靈活地足夠去容納多種不同的數(shù)據(jù)表示,其他的兩個模板參數(shù):
Map<typename MatrixType,int MapOptions,typename StrideType>MapOptions標識指針是否是對齊的(Aligned),默認是Unaligned。
StrideType表示內存數(shù)組的組織方式:行列的步長。
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.536Eigen提供的函數(shù)都兼容Map對象。
改變mapped數(shù)組
Map對象聲明后,可以通過C++的placement new語法來改變Map的數(shù)組。
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總結
以上是生活随笔為你收集整理的Eigen教程(8)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode:371.Sum Of
- 下一篇: 第十七篇:获取 / 修改进程资源限制