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

原文链接: https://www.cnblogs.com/houkai/p/6349981.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    Eigen教程(8)

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/248450

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月14日 上午2:54
下一篇 2023年2月14日 上午2:56

相关推荐