Eigen的使用

原文https://blog.csdn.net/u012541187/article/details/53420432

1、Eigen 的包含設置

#include <Eigen>
#include <Eigen/Dense>

using namespace Eigen;

2、Eigen 的基本計算

2.1 Eigen中矩陣的定義

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

2.2 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

2.3 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)'線性分佈的數組

2.4 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)同上

2.5 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]) 交換列

2.6 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)共軛矩陣

2.7 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;

2.8 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)這個也是單個元素的操作

2.9 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) 或運算

2.10 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>

2.11 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

2.12 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()

2.13 Eigen 矩陣特徵值

// Eigen                          // Matlab
A.eigenvalues();                  // eig(A);特徵值
EigenSolver<Matrix3d> eig(A);     // [vec val] = eig(A)
eig.eigenvalues();                // diag(val)與前邊的是一樣的結果
eig.eigenvectors();               // vec 特徵值對應的特徵向量

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章