Eigen 库常用基本用法 备忘

2023-05-16

ps: eigen 看到的时候较多,自己写的时候总有一些用法想不起来具体函数名,特此总结一下以备忘。

官方doc: eigen 官网最权威

目录

Eigen 矩阵定义

Eigen 基础使用

Eigen 特殊矩阵生成

Eigen 矩阵分块

Eigen 矩阵元素交换

Eigen 矩阵转置

Eigen 矩阵乘积

Eigen 矩阵单个元素操作

Eigen 矩阵化简

Eigen 矩阵点乘

Eigen 矩阵类型转换

Eigen 求解线性方程组 Ax = b

Eigen 矩阵特征值

参考链接


Eigen 矩阵定义

#include <Eigen/Dense>

Matrix<double, 3, 3> A;               // Fixed rows and cols. Same as Matrix3d.
Matrix<double, 3, Dynamic> B;         // Fixed rows, dynamic cols.
Matrix<double, Dynamic, Dynamic> C;   // Full dynamic. Same as MatrixXd.
Matrix<double, 3, 3, RowMajor> E;     // Row major; default is column-major.
Matrix3f P, Q, R;                     // 3x3 float matrix.
Vector3f x, y, z;                     // 3x1 float matrix.
RowVector3f a, b, c;                  // 1x3 float matrix.
VectorXd v;                           // Dynamic column vector of doubles
// Eigen          // Matlab           // comments
x.size()          // length(x)        // vector size
C.rows()          // size(C,1)        // number of rows
C.cols()          // size(C,2)        // number of columns
x(i)              // x(i+1)           // Matlab is 1-based
C(i,j)            // C(i+1,j+1)       //

Eigen 基础使用

// Basic usage
// Eigen        // Matlab           // comments
x.size()        // length(x)        // vector size
C.rows()        // size(C,1)        // number of rows
C.cols()        // size(C,2)        // number of columns
x(i)            // x(i+1)           // Matlab is 1-based
C(i, j)         // C(i+1,j+1)       //

A.resize(4, 4);   // Runtime error if assertions are on.
B.resize(4, 9);   // Runtime error if assertions are on.
A.resize(3, 3);   // Ok; size didn't change.
B.resize(3, 9);   // Ok; only dynamic cols changed.
                  
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.fill(10);       // Fill A with all 10's.

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        // 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)'

Eigen 矩阵分块

// Matrix slicing and blocks. All expressions listed here are read/write.
// Templated size versions are faster. Note that Matlab is 1-based (a size N
// vector is x(1)...x(N)).
// Eigen                           // Matlab
x.head(n)                          // x(1:n)
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)
P.block<rows, cols>(i, j)          // P(i+1 : i+rows, j+1 : j+cols)
P.row(i)                           // P(i+1, :)
P.col(j)                           // P(:, j+1)
P.leftCols<cols>()                 // P(:, 1:cols)
P.leftCols(cols)                   // P(:, 1:cols)
P.middleCols<cols>(j)              // P(:, j+1:j+cols)
P.middleCols(j, cols)              // P(:, j+1:j+cols)
P.rightCols<cols>()                // P(:, end-cols+1:end)
P.rightCols(cols)                  // P(:, end-cols+1:end)
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)
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 矩阵元素交换

// Of particular note is Eigen's swap function which is highly optimized.
// 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)
R.conjugate()                      // conj(R)

Eigen 矩阵乘积

// All the same as Matlab, but matlab doesn't have *= style operators.
// 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
R.array() -= s;           // R = R - 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.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)
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 矩阵点乘

// Dot products, norms, etc.
// Eigen                  // Matlab
x.norm()                  // norm(x).    Note that norm(R) doesn't work in Eigen.
x.squaredNorm()           // dot(x, x)   Note the equivalence is not true for complex
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));  // 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));  // 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 矩阵特征值

// Eigenvalue problems
// Eigen                          // Matlab
A.eigenvalues();                  // eig(A);
EigenSolver<Matrix3d> eig(A);     // [vec val] = eig(A)
eig.eigenvalues();                // diag(val)
eig.eigenvectors();               // vec
// For self-adjoint matrices use SelfAdjointEigenSolver<>

参考链接

C++矩阵库 Eigen 快速入门 - python27 - 博客园

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Eigen 库常用基本用法 备忘 的相关文章

  • echart横坐标字体样式问题 xAxis属性问题

    xAxis type 34 category 34 data this problemCity citys axisTick alignWithLabel true axisLabel show true textStyle fontSiz
  • STM32F103程序设计-2-使用STLINK下载程序的两种方法

    市场上常用的仿真器有三种 xff1a STLINK ULINK 及 JLINK 其中官方出品的是 STLINK xff0c 价格在 120 元左右 STLINK 包含三部分 xff1a 数据线 USB 线及仿真器本身 驱动程序的安装方法 x
  • Ubuntu 更换源不成功 sudo apt-get update 失败问题总结

    安装NVIDIA px2 ros总是失败 xff0c NVIDIA DRIVE px2是arm64架构 xff0c 跟平常的笔记本 xff0c 台式机不一样 xff0c 不过也有一定的借鉴意义 问题都是类似的 比如这次我遇到如下问题 xff
  • OpenFOAM-工具Tools学习笔记

    记录OpenFOAM中工具的学习和使用 xff0c 持续更新和整理 surfaceAdd 该工具可以将两个stl合并到一个文件中 使用命令行开关 mergerregions将具有相同名称的区域连接到一个区域 否则 xff0c 这两个区域将保
  • 【OpenFOAM】学习网址汇集

    收藏了好多关于OpenFOAM学习网址的帖子文章等 xff0c 时间久了自己都忘了 xff0c 建立一个自己的吧 xff0c 这下应该舒服了 https www openfoam com https openfoam org https o
  • C语言初学1--基础

    C语言基础学习记录 学习视频如下 https www bilibili com video BV1q54y1q79w spm id from 61 333 999 0 0 amp vd source 61 7442270a1c7e13b4d
  • C语言初学2--分支和循环

    C语言基础学习记录 学习视频如下 https www bilibili com video BV1q54y1q79w spm id from 61 333 999 0 0 amp vd source 61 7442270a1c7e13b4d
  • 【OpenFOAM】topoSet学习笔记

    非常好的文章 xff1a OpenFOAM初学心得 xff08 五 xff09 内部边界的设定 xff08 topoSet与createBaffles工具 xff09 区域划定工具topoSet 详细的topoSetDict 见 etc c
  • 【OpenFOAM】-olaFlow-算例1- baseWaveFlume

    算例路径 olaFlow tutorials baseWaveFlume 算例描述 一个基础的二维波浪水槽 学习目标 olaFlow 求解器的造波 消波方法和算例设置 算例快照 图1 波浪模拟结果 图2 算例网格 文件结构 span cla
  • WPI交通信号灯数据集格式转换成VOC2007

    WPI交通信号灯数据集格式转换成VOC2007 1 简述 初学交通信号灯目标检测时 xff0c 总是苦于找不到合适的交通灯数据集 即使找到了数据集 xff0c 也往往因为格式不同而无法直接使用 因为大部分目标检测代码都只支持VOC或COCO
  • 【OpenFOAM】-olaFlow-算例2- breakwater

    算例路径 olaFlow tutorials breakwater 算例描述 波浪对防波堤的作用 堤身为孔隙可渗透结构 堤顶沉箱为不可渗透结构 学习目标 渗透模型 可渗结构设置 孔隙材料各项参数设置 算例快照 图1 防波堤越浪模拟结果 图2
  • 【OpenFOAM】-olaFlow-算例3- currentWaveFlume

    算例路径 olaFlow tutorials currentWaveFlume 算例描述 波流耦合模拟 该算例提供了四种工况 1 Waves and forward current 2 Waves and backward current
  • 【OpenFOAM】-olaFlow-算例4- irreg45degTank

    算例路径 olaFlow tutorials irreg45degTank 算例描述 不规则波浪模拟 学习目标 不规则波浪模拟 olaFlow中单向不规则波采用线性波浪叠加法生成 基本原理如图2所受 需要提供对应波谱的周期 波高和相位的离散
  • 【OpenFOAM】-olaFlow-算例5- oppositeSolitariesFlume

    算例路径 olaFlow tutorials oppositeSolitariesFlume 算例描述 两列反向的孤立波相互作用 学习目标 熟练掌握olaFlow的造波设置 波浪方向与消波方向设置 算例快照 图1 两列反向孤立波相互作用 文
  • 【OpenFOAM】-olaFlow-算例6- waveFloatingObject

    算例路径 olaFlow tutorials waveFloatingObject 算例描述 波浪作用下的浮体的刚体运动 属于流固耦合 FSI 问题 学习目标 动网格设置和使用 网格变形控制 浮体的物理参数设置 浮体做刚体运动的约束设置 算
  • 【OpenFOAM】-olaFlow-算例7-波面自适应网格

    算例路径 none 算例描述 波面附近采用自适应网格划分 学习目标 动网格设置和使用 dynamicFvMesh dynamicRefineFvMesh 的各参数含义 学习体会 1 在结构附近的加密网格 自适应网格依然会对细网格进一步细化
  • 【OpenFOAM】-olaFlow-算例8-setOlaFlume

    算例路径 olaFlow tutorials setOlaFlume 算例描述 不规则底部的二维波浪水槽 且波场被 setOla 工具设置为初始条件 学习目标 使用 setOla 工具设置初始条件为波浪场 不规则底部数值波浪水槽的设置 学习
  • 【OpenFOAM】-olaFlow-算例9-pistonFlumeABS

    算例路径 olaFlow tutorials pistonFlumeABS 算例描述 采用 piston 形式的动边界进行消波 学习目标 了解 olaDyMFlow 的使用 理解动网格使用和参数设置 理解 dynamicMotionSolv
  • 【OpenFOAM】-olaFlow-算例10-wavemakerTank

    算例路径 olaFlow tutorials wavemakerTank 算例描述 采用 Flap和Piston两种方式的动网格进行造波 学习目标 了解 olaDyMFlow 的使用 理解动网格使用和参数设置 理解 dynamicMotio
  • 【OpenFOAM】-算例解析合集(备份目录)

    OpenFOAM 算例解析合集 OlaFlowinterFoampimpleFoam OlaFlow OpenFOAM olaFlow 算例1 baseWaveFlume OpenFOAM olaFlow 算例2 breakwater Op

随机推荐