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