Eigen API汇总 & 简介

API (important)


// 参考 - http://eigen.tuxfamily.org/dox/AsciiQuickReference.txt
// 一个关于Eigen的快速参考
// Matlab和Eigen的对应用法
// Main author: Keir Mierle
// 注释:张学志

#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 的浮点型矩阵
Vector3f x, y, z;                     // 3x1 的浮点型矩阵(列向量)
RowVector3f a, b, c;                  // 1x3 的浮点型矩阵(行向量)
VectorXd v;                           // 动态大小的双精度列向量
double s;                            

// 基本用法
// Eigen          // Matlab           // 注释
x.size()          // length(x)        // 向量的长度
C.rows()          // size(C,1)        // 矩阵的行数
C.cols()          // size(C,2)        // 矩阵的列数
x(i)              // x(i+1)           // 访问向量元素(Matlab的下标从1开始计数)
C(i,j)            // C(i+1,j+1)       // 访问矩阵元素

A.resize(4, 4);   // 如果开启了断言,将会出现运行时错误。
B.resize(4, 9);   // 如果开启了断言,将会出现运行时错误。
A.resize(3, 3);   // 运行正常,矩阵的大小没有变化及。(A的行数和列数都是固定大小的)
B.resize(3, 9);   // 运行正常,仅动态列数发生了变化。(B的列数是动态变化的)
                  
A << 1, 2, 3,     // 初始化A。元素也可以是矩阵,先按列堆叠,再按行堆叠。
     4, 5, 6,     
     7, 8, 9;     
B << A, A, A;     // B 是3个A水平排列
A.fill(10);       // 将A的所有元素填充为10

// 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 返回范围为(-1, 1)的均匀分布的随机数
C.setRandom(rows,cols)                      // C = rand(rows,cols)*2-1      //返回范围为(-1, 1)的均匀分布的随机数
VectorXd::LinSpaced(size,low,high)          // linspace(low,high,size)'     //返回size个等差数列,第一个数为low,最后一个数为high
v.setLinSpaced(size,low,high)               // v = linspace(low,high,size)' //返回size个等差数列,第一个数为low,最后一个数为high
VectorXi::LinSpaced(((hi-low)/step)+1,      // low:step:hi                  //以step为步长的等差数列。((hi-low)/step)+1为个数
                    low,low+step*(size-1))  //


// Matrix 切片和块。下面列出的所有表达式都是可读/写的。
// 使用模板参数更快(如第2个)。注意:Matlab是的下标是从1开始的。
// Eigen                           // Matlab                        // 注释
x.head(n)                          // x(1:n)                        //前n个元素
x.head<n>()                        // x(1:n)                        //前n个元素
x.tail(n)                          // x(end - n + 1: end)           //倒数n个元素
x.tail<n>()                        // x(end - n + 1: end)           //倒数n个元素
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) //块
P.block<rows, cols>(i, j)          // P(i+1 : i+rows, j+1 : j+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)              //中间cols列
P.middleCols(j, cols)              // P(:, j+1:j+cols)              //中间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, :)                  //前rows行
P.topRows(rows)                    // P(1:rows, :)                  //前rows行
P.middleRows<rows>(i)              // P(i+1:i+rows, :)              //中间rows行
P.middleRows(i, rows)              // P(i+1:i+rows, :)              //中间rows行
P.bottomRows<rows>()               // P(end-rows+1:end, :)          //最后rows行
P.bottomRows(rows)                 // P(end-rows+1:end, :)          //最后rows行
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) //右下角块
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(:, j)
R.col(j1).swap(mat1.col(j2));      // R(:, [j1 j2]) = R(:, [j2, j1]) //交换列


// Views, transpose, etc;
// 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.rowwise().reverse()              // fliplr(R)             // 水平翻转
R.colwise().reverse()              // flipud(R)             // 垂直翻转
R.replicate(i,j)                   // repmat(P,i,j)         // 复制矩阵,垂直复制i个,水平复制j个


// 四则运算,和Matlab相同。但Matlab中不能使用*=这样的赋值运算符
// 矩阵 - 向量    矩阵 - 矩阵      矩阵 - 标量
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;

                   
// 逐像素操作Vectorized operations on each element independently
// Eigen                       // Matlab        //注释
R = P.cwiseProduct(Q);         // R = P .* Q    //逐元素乘法
R = P.array() * s.array();     // R = P .* s    //逐元素乘法(s为标量)
R = P.cwiseQuotient(Q);        // R = P ./ Q    //逐元素除法
R = P.array() / Q.array();     // R = P ./ Q    //逐元素除法
R = P.array() + s.array();     // R = P + s     //逐元素加法(s为标量)
R = P.array() - s.array();     // R = P - s     //逐元素减法(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        //逐元素比较运算
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和P的最大值
R.array().max(P.array())       // max(R, P)     //逐元素计算R和P的最大值
R.cwiseMin(P)                  // min(R, P)     //逐元素计算R和P的最小值
R.array().min(P.array())       // min(R, P)     //逐元素计算R和P的最小值
R.cwiseAbs()                   // abs(P)        //逐元素计算R和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)                             //根据R的元素值是否小于s,选择P和Q的对应元素
R = (Q.array()==0).select(P,A) // R(Q==0) = P(Q==0) R(Q!=0) = P(Q!=0)         //根据Q中元素等于零的位置选择P中元素
R = P.unaryExpr(ptr_fun(func)) // R = arrayfun(func, P)     // 对P中的每个元素应用func函数


// 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)                 //按列求和
R.rowwise().sum()         // sum(R, 2) or sum(R')'  //按行求和
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                  // Matlab           // 注释
x.norm()                  // norm(x).         //范数(注意:Eigen中没有norm(R))
x.squaredNorm()           // dot(x, x)        //平方和(注意:对于复数而言,不等价)
x.dot(y)                  // dot(x, y)        //点积
x.cross(y)                // cross(x, y)      //交叉积,需要头文件 #include <Eigen/Geometry>


 类型转换
// 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)            //虚部
// 如果变换前后的类型相同,不做任何事情。


// 注意:Eigen中,绝大多数的涉及多个操作数的运算都要求操作数具有相同的类型
MatrixXf F = MatrixXf::Zero(3,3);
A += F;                // 非法。Matlab中允许。(单精度+双精度)
A += F.cast<double>(); // 将F转换成double,并累加。(一般都是在使用时临时转换)


// Eigen 可以将已存储数据的缓存 映射成 Eigen矩阵
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);                    // 将 data 复制到 mat2x2
Matrix2i::Map(data) = 2*mat2x2;           // 使用 2*mat2x2 覆写data的元素 
MatrixXi::Map(data, 2, 2) += mat2x2;      // 将 mat2x2 加到 data的元素上 (当编译时不知道大小时,可选语法)


// 求解线性方程组 Ax = b。结果保存在x中。      Matlab: x = A \ b.
x = A.ldlt().solve(b));  // A sym. p.s.d.    #include <Eigen/Cholesky>
x = A.llt() .solve(b));  // A sym. p.d.      #include <Eigen/Cholesky>
x = A.lu()  .solve(b));  // 稳定,快速       #include <Eigen/LU>
x = A.qr()  .solve(b));  // No pivoting.     #include <Eigen/QR>        //Eigen 3.3.2中没有?
x = A.svd() .solve(b));  // 稳定,慢速       #include <Eigen/SVD>       //Eigen 3.3.2中没有?
// .ldlt() -> .matrixL() and .matrixD()                         //?
// .llt()  -> .matrixL()                                        //?
// .lu()   -> .matrixL() and .matrixU()                         //?
// .qr()   -> .matrixQ() and .matrixR()                         //?
// .svd()  -> .matrixU(), .singularValues(), and .matrixV()     //?


// 特征值问题
// Eigen                          // Matlab
A.eigenvalues();                  // eig(A);
EigenSolver<Matrix3d> eig(A);     // [vec val] = eig(A)
eig.eigenvalues();                // diag(val)          //特征值,向量形式
eig.eigenvectors();               // vec                //特征向量,矩阵形式
// 对于自伴矩阵(Hermitian矩阵或对称矩阵),使用SelfAdjointEigenSolver<>

Eigen库使用指南

1.模块和头文件

  • Core #include<Eigen/Core>,包含Matrix和Array类,基础的线性代数运算和数组操作。
  • Geometry #include<Eigen/Geometry>,包含旋转,平移,缩放,2维和3维的各种变换。
  • LU #include<Eigen/LU>,包含求逆,行列式,LU分解。
  • Cholesky #include<Eigen/Cholesky>,包含LLT和LDLT Cholesky分解。
  • SVD #include<Eigen/SVD>,包含SVD分解。
  • QR #include<Eigen/QR>,包含QR分解。
  • Eigenvalues #include<Eigen/Eigenvalues>,包含特征值,特征向量分解。
  • Sparse #include<Eigen/Sparse>,包含稀疏矩阵的存储和运算。
  • Dense #include<Eigen/Dense>,包含了Core/Geometry/LU/Cholesky/SVD/QR/Eigenvalues模块。
  • Eigen #include<Eigen/Eigen>,包含Dense和Sparse。

2. Matrix类

所有矩阵和向量都是Matrix模板类的对象,Matrix类有6个模板参数,主要使用前三个,剩下的使用默认值。

Matrix<typename Scalar, 
       int RowsAtCompileTime, 
       int ColsAtCompileTime,
       int Options = 0,
       int MaxRowsAtCompileTime = RowsAtCompileTime,
       int MaxColsAtCompileTime = ColsAtCompileTime>
# Scalar 元素类型
# RowsAtCompileTime 行
# ColsAtCompileTime 列
# 例 typedef Matrix<int, 3, 3> Matrix3i;
# Options 比特标志位
# MaxRowsAtCompileTime和MaxColsAtCompileTime表示在编译阶段矩阵的上限。

# 列向量
typedef Matrix<double, 3, 1> Vector3d;
# 行向量
typedef Matrix<float, 1, 3> RowVector3f;

# 动态大小
typedef Matrix<double, Dynamic, Dynamic> MatrixXd;
typedef Matrix<float, Dynamic, 1> VectorXf;
type
  • 默认构造时,指定大小的矩阵,只分配相应大小的空间,不进行初始化。
  • 动态大小的矩阵,则未分配空间。
  • []操作符可以用于向量元素的获取,但不能用于matrix。
  • matrix的大小可以通过rows(), cols(), size()获取,resize()可以重新调整矩阵大小。

3. 矩阵与向量的运算

Eigen不支持类型自动转化,因此矩阵元素类型必须相同。
支持+, -, +=, -=, *, /, *=, /=基础四则运算。
转置和共轭

MatrixXcf a = MatrixXcf::Random(3,3);
a.transpose();  # 转置
a.conjugate();  # 共轭
a.adjoint();       # 共轭转置(伴随矩阵)
# 对于实数矩阵,conjugate不执行任何操作,adjoint等价于transpose
a.transposeInPlace() #原地转置

Vector3d v(1,2,3);
Vector3d w(4,5,6);
v.dot(w);    # 点积
v.cross(w);  # 叉积

Matrix2d a;
a << 1, 2, 3, 4;
a.sum();      # 所有元素求和
a.prod();      # 所有元素乘积
a.mean();    # 所有元素求平均
a.minCoeff();    # 所有元素中最小元素
a.maxCoeff();   # 所有元素中最大元素
a.trace();      # 迹,对角元素的和
# minCoeff和maxCoeff还可以返回结果元素的位置信息
int i, j;
a.minCoeff(&i, &j);

4. Array类

Array是个类模板,前三个参数必须指定,后三个参数可选。

Array<typename Scalar,
      int RowsAtCompileTime,
      int ColsAtCompileTime>
# 常见类定义
typedef Array<float, Dynamic, 1> ArrayXf
typedef Array<float, 3, 1> Array3f
typedef Array<double, Dynamic, Dynamic> ArrayXXd
typedef Array<double, 3, 3> Array33d

ArrayXf a = ArrayXf::Random(5);
a.abs();    # 绝对值
a.sqrt();    # 平方根
a.min(a.abs().sqrt());  # 两个array相应元素的最小值
  • 当执行array*array时,执行的是相应元素的乘积,所以两个array必须具有相同的尺寸。
  • Matrix对象——>Array对象:.array()函数
  • Array对象——>Matrix对象:.matrix()函数

5. Vector的块操作

在这里插入图片描述

6. 归约,迭代器,广播

范数计算

  • squareNorm():L2范数,等价于计算vector自身点积
  • norm():返回`squareNorm的开方根
  • .lpNorm<p>():p范数,p可以取Infinity,表无穷范数

布尔归约

  • all()=true: matrix或array中所有元素为true
  • any()=true: 到少有一个为true
  • count(): 返回true元素个数
// sample
ArrayXXf A(2, 2);
A << 1,2,3,4;
(A > 0).all();
(A > 0).any();
(A > 0).count();

迭代器,获取某元素位置

// sample
Eigen::MatrixXf m(2,2);
m << 1,2,3,4;
MatrixXf::Index maxRow, maxCol;
float max = m.maxCoeff(&minRow, &minCol);

部分归约,

// sample
Eigen::MatrixXf mat(2,3);
mat << 1,2,3,
       4,5,6;
std::cout << mat.colwise().maxCoeff();
// output: 4, 5, 6
// mat.rowWise() the same as before

广播,针对vector,沿行或列重复构建一个matrix。

// sample
Eigen::MatrixXf mat(2,3);
Eigen::VectorXf v(2);

mat << 1,2,3,4,5,6;
v << 0,1;
mat.colwise() += v;
// output: 1, 2, 3, 5, 6, 7

7. Map类

Map类用于利用数据的内在,并将其转为Eigen类型。
定义:
Map<Matrix<typename Scalar, int RowAtCompileTime, int ColsAtCompileTime> >
通过Map来reshape矩阵的形状。

8. 混淆问题

使用eval()函数解决把右值赋值为一个临时矩阵,再赋给左值时可能有造成的混淆。如:

MatrixXi mat(3,3);
mat << 1,2,3, 4,5,6, 7,8,9;
mat.bottomRightCorner(2,2) = mat.topLeftCorner(2,2).eval();

原地操作的一类函数:

普通函数 inplace函数
MatrixBase::adjoint() MatrixBase::adjointInPlace()
DenseBase::reverse() DenseBase::reverseInPlace()
LDLT::solve() LDLT::solveInPlace()
LLT::solve() LLT::solveInPlace()
TriangularView::solve() TriangularView::solveInPlace()
DenseBase::transpose() DenseBase::transposeInPlace()
  • 当相同的矩阵或array出现在等式左右时,容易出现混淆
  • 当确定不会出现混淆时,可以使用noalias()
  • 混淆出现时,可以使用eval()和xxxInPlace()函数解决

ref:

https://www.jianshu.com/p/931dff3b1b21

猜你喜欢

转载自blog.csdn.net/weixin_41521681/article/details/113705800
今日推荐