Eigen(7)Map类

这里将解释Eigen如何与原生raw C/C++ 数组混合编程。

1. 简介

    Eigen中定义了一系列的vectormatrix,相比copy数据,更一般的方式是复用数据的内存,将它们转变为Eigen类型。Map类很好地实现了这个功能。

2. 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

3. 使用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对象。

4. 改变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

 

  • 10
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值