Eigen 基本使用方法

Eigen中矩阵的定义

#include <Eigen/Dense>                  // 基本函数只需要包含这个头文件
Matrix<double, 3, 3> A;                 // 固定了行数和列数的矩阵和Matrix3d一致.
Matrix<double, 3, Dynamic> B;           // 固定行数.
Matrix<double, Dynamic, Dynamic> C;     // 和MatrixXd一致.
Matrix<double, 3, 3, RowMajor> E;       // 按行存储; 默认按列存储.
Matrix3f P, Q, R;                       // 3x3 float 矩阵.
Vector3f x, y, z;                       // 3x1 float 列向量.
RowVector3f a, b, c;                    // 1x3 float 行向量.
VectorXd v;                             // 动态长度double型列向量
// Eigen          // Matlab             // comments
x.size()          // length(x)          // 向量长度
C.rows()          // size(C,1)          // 矩阵行数
C.cols()          // size(C,2)          // 矩阵列数
x(i)              // x(i+1)             // 下标0开始
C(i,j)            // C(i+1,j+1)         //

Eigen 中矩阵的基本使用方法

A.resize(4, 4);   // 如果越界触发运行时错误.
B.resize(4, 9);   // 如果越界触发运行时错误.
A.resize(3, 3);   // Ok; 没有越界.
B.resize(3, 9);   // Ok; 没有越界.

A << 1, 2, 3,     // Initialize A. The elements can also be
     4, 5, 6,     // matrices, which are stacked along cols
     7, 8, 9;     // and then the rows are stacked.
B << A, A, A;     // B is three horizontally stacked A's.   三行A
A.fill(10);       // Fill A with all 10's.                  全10

Eigen 特殊矩阵生成

// 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 = ones(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        // 元素随机在-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)'线性分布的数组

Eigen 矩阵分块

// Eigen                           // Matlab
x.head(n)                          // x(1:n)    用于数组提取前n个[vector]
x.head<n>()                        // x(1:n)    同理
x.tail(n)                          // x(end - n + 1: end)同理
x.tail<n>()                        // x(end - n + 1: end)同理
x.segment(i, n)                    // x(i+1 : i+n)同理
x.segment<n>(i)                    // x(i+1 : i+n)同理
P.block(i, j, rows, cols)          // P(i+1 : i+rows, j+1 : j+cols)i,j开始,rows行cols列
P.block<rows, cols>(i, j)          // P(i+1 : i+rows, j+1 : j+cols)i,j开始,rows行cols列
P.row(i)                           // P(i+1, :)i行
P.col(j)                           // P(:, j+1)j列
P.leftCols<cols>()                 // P(:, 1:cols)左边cols列
P.leftCols(cols)                   // P(:, 1:cols)左边cols列
P.middleCols<cols>(j)              // P(:, j+1:j+cols)中间从j数cols列
P.middleCols(j, cols)              // P(:, j+1:j+cols)中间从j数cols列
P.rightCols<cols>()                // P(:, end-cols+1:end)右边cols列
P.rightCols(cols)                  // P(:, end-cols+1:end)右边cols列
P.topRows<rows>()                  // P(1:rows, :)同列
P.topRows(rows)                    // P(1:rows, :)同列
P.middleRows<rows>(i)              // P(i+1:i+rows, :)同列
P.middleRows(i, rows)              // P(i+1:i+rows, :)同列
P.bottomRows<rows>()               // P(end-rows+1:end, :)同列
P.bottomRows(rows)                 // P(end-rows+1:end, :)同列
P.topLeftCorner(rows, cols)        // P(1:rows, 1:cols)上左角rows行,cols列
P.topRightCorner(rows, cols)       // P(1:rows, end-cols+1:end)上右角rows行,cols列
P.bottomLeftCorner(rows, cols)     // P(end-rows+1:end, 1:cols)下左角rows行,cols列
P.bottomRightCorner(rows, cols)    // P(end-rows+1:end, end-cols+1:end)下右角rows行,cols列
P.topLeftCorner<rows,cols>()       // P(1:rows, 1:cols)同上
P.topRightCorner<rows,cols>()      // P(1:rows, end-cols+1:end)同上
P.bottomLeftCorner<rows,cols>()    // P(end-rows+1:end, 1:cols)同上
P.bottomRightCorner<rows,cols>()   // P(end-rows+1:end, end-cols+1:end)同上

Eigen 矩阵元素交换

// Eigen                           // Matlab
R.row(i) = P.col(j);               // R(i, :) = P(:, i)交换列为行
R.col(j1).swap(mat1.col(j2));      // R(:, [j1 j2]) = R(:, [j2, j1]) 交换列

Eigen 矩阵转置

// Views, transpose, etc; all read-write except for .adjoint().
// Eigen                           // Matlab
R.adjoint()                        // R' 伴随矩阵
R.transpose()                      // R.' or conj(R')转置
R.diagonal()                       // diag(R)对角
x.asDiagonal()                     // diag(x)对角阵(没有重载<<)
R.transpose().colwise().reverse(); // rot90(R)所有元素逆时针转了90度
R.conjugate()                      // conj(R)共轭矩阵

Eigen 矩阵乘积

// 与Matlab一致, 但是matlab不支持*=等形式的运算.
// Matrix-vector.  Matrix-matrix.   Matrix-scalar.
y  = M*x;          R  = P*Q;        R  = P*s;
a  = b*M;          R  = P - Q;      R  = s*P;
a *= M;            R  = P + Q;      R  = P/s;
                   R *= Q;          R  = s*P;
                   R += Q;          R *= s;
                   R -= Q;          R /= s;

Eigen 矩阵单个元素操作

// Vectorized operations on each element independently
// Eigen                  // Matlab
R = P.cwiseProduct(Q);    // R = P .* Q 对应点相乘
R = P.array() * s.array();// R = P .* s 对应点相乘
R = P.cwiseQuotient(Q);   // R = P ./ Q 对应点相除
R = P.array() / Q.array();// R = P ./ Q对应点相除
R = P.array() + s.array();// R = P + s对应点相加
R = P.array() - s.array();// R = P - s对应点相减
R.array() += s;           // R = R + s全加s
R.array() -= s;           // R = R - s全减s
R.array() < Q.array();    // R < Q 以下的都是针对矩阵的单个元素的操作
R.array() <= Q.array();   // R <= Q矩阵元素比较,会在相应位置置0或1
R.cwiseInverse();         // 1 ./ P
R.array().inverse();      // 1 ./ P
R.array().sin()           // sin(P) 
R.array().cos()           // cos(P)
R.array().pow(s)          // P .^ s
R.array().square()        // P .^ 2
R.array().cube()          // P .^ 3
R.cwiseSqrt()             // sqrt(P)
R.array().sqrt()          // sqrt(P)
R.array().exp()           // exp(P)
R.array().log()           // log(P)
R.cwiseMax(P)             // max(R, P) 对应取大
R.array().max(P.array())  // max(R, P) 对应取大
R.cwiseMin(P)             // min(R, P) 对应取小
R.array().min(P.array())  // min(R, P) 对应取小
R.cwiseAbs()              // abs(P) 绝对值
R.array().abs()           // abs(P) 绝对值
R.cwiseAbs2()             // abs(P.^2) 绝对值平方
R.array().abs2()          // abs(P.^2) 绝对值平方
(R.array() < s).select(P,Q);  // (R < s ? P : Q)这个也是单个元素的操作

Eigen 矩阵化简

// Reductions.
int r, c;
// Eigen                  // Matlab
R.minCoeff()              // min(R(:))最小值
R.maxCoeff()              // max(R(:))最大值
s = R.minCoeff(&r, &c)    // [s, i] = min(R(:)); [r, c] = ind2sub(size(R), i);
s = R.maxCoeff(&r, &c)    // [s, i] = max(R(:)); [r, c] = ind2sub(size(R), i);
R.sum()                   // sum(R(:))求和
R.colwise().sum()         // sum(R)列求和1×N
R.rowwise().sum()         // sum(R, 2) or sum(R')'行求和N×1
R.prod()                  // prod(R(:))所有乘积
R.colwise().prod()        // prod(R)列乘积
R.rowwise().prod()        // prod(R, 2) or prod(R')'行乘积
R.trace()                 // trace(R)迹
R.all()                   // all(R(:))且运算
R.colwise().all()         // all(R) 且运算
R.rowwise().all()         // all(R, 2) 且运算
R.any()                   // any(R(:)) 或运算
R.colwise().any()         // any(R) 或运算
R.rowwise().any()         // any(R, 2) 或运算

Eigen 矩阵点乘

// Dot products, norms, etc.
// Eigen                  // Matlab
x.norm()                  // norm(x).    模
x.squaredNorm()           // dot(x, x)   平方和
x.dot(y)                  // dot(x, y)
x.cross(y)                // cross(x, y) Requires #include <Eigen/Geometry>

Eigen 矩阵类型转换

 Type conversion
// Eigen                           // Matlab
A.cast<double>();                  // double(A)
A.cast<float>();                   // single(A)
A.cast<int>();                     // int32(A) 向下取整
A.real();                          // real(A)
A.imag();                          // imag(A)
// if the original type equals destination type, no work is done

Eigen 求解线性方程组 Ax = b

// Solve Ax = b. Result stored in x. Matlab: x = A \ b.
x = A.ldlt().solve(b));  // #include <Eigen/Cholesky>LDLT分解法实际上是Cholesky分解法的改进
x = A.llt() .solve(b));  // A sym. p.d.      #include <Eigen/Cholesky>
x = A.lu()  .solve(b));  // Stable and fast. #include <Eigen/LU>
x = A.qr()  .solve(b));  // No pivoting.     #include <Eigen/QR>
x = A.svd() .solve(b));  // Stable, slowest. #include <Eigen/SVD>
// .ldlt() -> .matrixL() and .matrixD()
// .llt()  -> .matrixL()
// .lu()   -> .matrixL() and .matrixU()
// .qr()   -> .matrixQ() and .matrixR()
// .svd()  -> .matrixU(), .singularValues(), and .matrixV()

内存映射创建矩阵

// Eigen can map existing memory into Eigen matrices.
float array[3];
Vector3f::Map(array).fill(10);            // create a temporary Map over array and sets entries to 10
int data[4] = {1, 2, 3, 4};
Matrix2i mat2x2(data);                    // copies data into mat2x2
Matrix2i::Map(data) = 2*mat2x2;           // overwrite elements of data with 2*mat2x2
MatrixXi::Map(data, 2, 2) += mat2x2;      // adds mat2x2 to elements of data (alternative syntax if size is not know at compile time)

 

Eigen 矩阵特征值

// Eigen                          // Matlab
A.eigenvalues();                  // eig(A);特征值
EigenSolver<Matrix3d> eig(A);     // [vec val] = eig(A)
eig.eigenvalues();                // diag(val)与前边的是一样的结果
eig.eigenvectors();               // vec 特征值对应的特征向量

Matrix类

在Eigen,所有的矩阵和向量都是Matrix模板类的对象,Vector只是一种特殊的矩阵(一行或者一列)。

Matrix有6个模板参数,主要使用前三个参数,剩下的有默认值。

Matrix<typename Scalar, int RowsAtCompileTime, int ColsAtCompileTime>

Scalar是表示元素的类型,RowsAtCompileTime为矩阵的行,ColsAtCompileTime为矩阵的列。

库中提供了一些类型便于使用,比如:

typedef Matrix<float, 4, 4> Matrix4f;

Vectors向量

列向量

typedef Matrix<float, 3, 1> Vector3f;

行向量

typedef Matrix<int, 1, 2> RowVector2i;

Dynamic

Eigen不只限于已知大小(编译阶段)的矩阵,有些矩阵的尺寸是运行时确定的,于是引入了一个特殊的标识符:Dynamic

typedef Matrix<double, Dynamic, Dynamic> MatrixXd;
typedef Matrix<int, Dynamic, 1> VectorXi;
Matrix<float, 3, Dynamic>

构造函数

默认的构造函数不执行任何空间分配,也不初始化矩阵的元素。

Matrix3f a;
MatrixXf b;

这里,a是一个3*3的矩阵,分配了float[9]的空间,但未初始化内部元素;b是一个动态大小的矩阵,定义是未分配空间(0*0)。

指定大小的矩阵,只是分配相应大小的空间,未初始化元素。

MatrixXf a(10,15);
VectorXf b(30);

这里,a是一个10*15的动态大小的矩阵,分配了空间但未初始化元素;b是一个30大小的向量,同样分配空间未初始化元素。

为了对固定大小和动态大小的矩阵提供统一的API,对指定大小的Matrix传递sizes也是合法的(传递也被忽略)。

Matrix3f a(3,3);

可以用构造函数提供4以内尺寸的vector的初始化。

Vector2d a(5.0, 6.0);
Vector3d b(5.0, 6.0, 7.0);
Vector4d c(5.0, 6.0, 7.0, 8.0);

获取元素

通过中括号获取元素,对于矩阵是:(行,列);对于向量,只是传递它的索引,以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;
}

输出

Here is the matrix m:
  3  -1
2.5 1.5
Here is the vector v:
4
3

m(index)也可以用于获取矩阵元素,但取决于matrix的存储顺序,默认是按列存储的,当然也可以改为按行。

[]操作符可以用于向量元素的获取,但是不能用于matrix,因为C++中[]不能传递超过一个参数。

逗号初始化

Matrix3f m;
m << 1, 2, 3,
     4, 5, 6,
     7, 8, 9;
std::cout << m;

resizing

matrix的大小可以通过rows()、cols()、size()获取,resize()可以重新调整动态matrix的大小。

#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
int main()
{
  MatrixXd m(2,5);
  m.resize(4,3);
  std::cout << "The matrix m is of size "
            << m.rows() << "x" << m.cols() << std::endl;
  std::cout << "It has " << m.size() << " coefficients" << std::endl;
  VectorXd v(2);
  v.resize(5);
  std::cout << "The vector v is of size " << v.size() << std::endl;
  std::cout << "As a matrix, v is of size "
            << v.rows() << "x" << v.cols() << std::endl;
}

输出:

The matrix m is of size 4x3
It has 12 coefficients
The vector v is of size 5
As a matrix, v is of size 5x1

如果matrix的实际大小不改变,resize函数不做任何操作。resize操作会执行析构函数:元素的值会被改变,如果不想改变执行 conservativeResize()。

为了统一API,所有的操作可用于指定大小的matrix,当然,实际中它不会改变大小。尝试去改变一个固定大小的matrix到一个不同的值,会出发警告失败。只有如下是合法的。

#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
int main()
{
  Matrix4d m;
  m.resize(4,4); // no operation
  std::cout << "The matrix m is of size "
            << m.rows() << "x" << m.cols() << std::endl;
}

assignment 和 resizing

assignment(分配)是复制一个矩阵到另外一个,操作符=。Eigen会自动resize左变量大小等于右变量大小,比如:

MatrixXf a(2,2);
std::cout << "a is of size " << a.rows() << "x" << a.cols() << std::endl;
MatrixXf b(3,3);
a = b;
std::cout << "a is now of size " << a.rows() << "x" << a.cols() << std::endl;

a is of size 2x2
a is now of size 3x3

当然,如果左边量是固定大小的,上面的resizing是不允许的。

固定尺寸 vs 动态尺寸

实际中,应该使用固定尺寸还是动态尺寸,简单的答案是:小的尺寸用固定的,大的尺寸用动态的。使用固定尺寸可以避免动态内存的开辟,固定尺寸只是一个普通数组。

Matrix4f mymatrix; 等价于 float mymatrix[16];

MatrixXf mymatrix(rows,columns); 等价于 float *mymatrix = new float[rows*columns];

使用固定尺寸(<=4*4)需要编译前知道矩阵大小,而且对于足够大的尺寸,如大于32,固定尺寸的收益可以忽略不计,而且可能导致栈崩溃。而且基于环境,Eigen会对动态尺寸做优化(类似于std::vector)

其他模板参数

上面只讨论了前三个参数,完整的模板参数如下:

Matrix<typename Scalar,
       int RowsAtCompileTime,
       int ColsAtCompileTime,
       int Options = 0,
       int MaxRowsAtCompileTime = RowsAtCompileTime,
       int MaxColsAtCompileTime = ColsAtCompileTime>

Options是一个比特标志位,这里,我们只介绍一种RowMajor,它表明matrix使用按行存储,默认是按列存储。Matrix<float, 3, 3, RowMajor>

MaxRowsAtCompileTime和MaxColsAtCompileTime表示在编译阶段矩阵的上限。主要是避免动态内存分配,使用数组。

Matrix<float, Dynamic, Dynamic, 0, 3, 4> 等价于 float [12]

一些方便的定义

Eigen定义了一些类型

  • MatrixNt = Matrix<type, N, N> 特殊地有 MatrxXi = Matrix<int, Dynamic, Dynamic>
  • VectorNt = Matrix<type, N, 1> 比如 Vector2f = Matrix<float, 2, 1>
  • RowVectorNt = Matrix<type, 1, N> 比如 RowVector3d = Matrix<double, 1, 3>

N可以是2,3,4或X(Dynamic)

t可以是i(int)、f(float)、d(double)、cf(complex)、cd(complex)等。

 

 

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值