Eigen库中矩阵的创建、初始化和赋值

3 篇文章 0 订阅
Eigen::Matrix4d rot;// 创建4行4列的double型矩阵(方阵)
rot << 1.0, 0.0, 0.0, 0.0,
		0.0, cos(p), -sin(p), 0.0,
		0.0, sin(p), cos(p), 0.0,
		0.0, 0.0, 0.0, 1.0;

Eigen::MatrixXd rot2(10,3);// 创建10行3列的double型矩阵
for(int i=0;i<10;++i)
{
   // 对矩阵进行初始化
   rot2(i,0)=i;
   rot2(i,1)=i;
   rot2(i,2)=i;
}

// 创建向量2*1的double型列向量,并初始化
Eigen::Vector2d u(1.0,2.9);
// 行向量
Eigen::Vector2d v=u.transpose();

点运算和叉运算
dot()执行点积,cross()执行叉积,点运算得到1*1的矩阵。当然,点运算也可以用u.adjoint()*v来代替。

#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
using namespace std;
int main()
{
  Vector3d v(1,2,3);
  Vector3d w(0,1,2);
  cout << "Dot product: " << v.dot(w) << endl;
  double dp = v.adjoint()*w; // automatic conversion of the inner product to a scalar
  cout << "Dot product via a matrix product: " << dp << endl;
  cout << "Cross product:\n" << v.cross(w) << endl;
}

访问元素
对于矩阵是(行,列),对于向量,可以通过中括号获取元素,也可以用小括号获取元素,只是传递它的索引,以0为起始。

#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
int main()
{
  MatrixXd m(2,2);
  m(0,0) = 3;
  m(1,0) = 2.5;
  m(0,1) = -1;
  m(1,1) = m(1,0) + m(0,1);
  std::cout << "Here is the matrix m:\n" << m << std::endl;
  VectorXd v(2);
  v(0) = 4;
  v(1) = v(0) - 1;
  std::cout << "Here is the vector v:\n" << v << std::endl;
  m.block<2,1>(0,1)=v;//坐标0行1列开始,将2行1列的块的元素用v覆盖;
  std::cout << "Here is the matrix m:\n" << m << std::endl;
  m.block(0,0,2,1)=v;//坐标0行0列开始,将2行1列的块的元素用v覆盖;
  std::cout << "Here is the matrix m:\n" << m << std::endl;
}

特殊矩阵

// Eigen                            // Matlab
MatrixXd::Identity(rows,cols)       // eye(rows,cols)
C.setIdentity(rows,cols)            // C = eye(rows,cols)
MatrixXd::Zero(rows,cols)           // zeros(rows,cols)
C.setZero(rows,cols)                // C = zeros(rows,cols)
MatrixXd::Ones(rows,cols)           // ones(rows,cols)
C.setOnes(rows,cols)                // C = ones(rows,cols)
MatrixXd::Random(rows,cols)         // rand(rows,cols)*2-1        // MatrixXd::Random returns uniform random numbers in (-1, 1).
C.setRandom(rows,cols)              // C = rand(rows,cols)*2-1
VectorXd::LinSpaced(size,low,high)  // linspace(low,high,size)'
v.setLinSpaced(size,low,high)       // v = linspace(low,high,size)'

存储顺序及选择
Matrix类模板中可以设定存储的方向,RowMajor表示行优先,ColMajor表示列优先。默认是列优先。
如何选择存储方式呢?
如果要和其他库合作开发,为了转化方便,可以选择同样的存储方式。
应用中涉及大量行遍历操作,应该选择行优先,寻址更快。反之亦然。
默认是列优先,而且大多库都是按照这个顺序的,默认的不失为较好的。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值