1. Settings of Eigen

1.1 Here Eigen3

  • Type sudo apt-get install libeigen3-dev to install Eigen3.
  • It will be installed in the default directory /usr/include/eigen3.
  • Just copy Eigen under /usr/include/eigen3 to the directory /usr/include.

1.2 Header files

1
2
#include <Eigen/Dense>
using namespace Eigen;

1.3 Tips

MatrixXd m(r, c); “X” means “dynamic”, “d” means basic data type “double”, “r” and “c” indicate no. of rows an columns.

MatrixXf m(r, c); “X” also means “dynamic”,“f” means “float”.

MatrixXcd c(r, c); “X” means “dynamic”,“c” means “complex”, “d” means “double”.

2. Basic numerical operations

2.1 Definitions of matrix in Eigen

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Matrix<double, 5, 5> M1;                // Fix rows and columns, same as Matrix5d.
Matrix<double, 4, Dynamic> M2;          // Fix rows.
Matrix<double, Dynamic, Dynamic> C;     // Same as MatrixXd.
Matrix<double, 3, 3, RowMajor> E;       // Storing according to rows, default is column majority.
Matrix3f P, Q, R;                       // Float maxtrix with size of 3 x 3.
Vector3f x, y, z;                       // Column vetor with 3 x 1.
RowVector3f a, b, c;                    // Row vector with 1 x 3.
VectorXd v;                             // Dynamic double vectors.
// In Eigen3      // In matlab           
v.size()          // length(v)          // Length of vector v.
C.rows()          // size(C,1)          // Rows of matrix.
C.cols()          // size(C,2)          // Columns of matrix.
v(i)              // v(i+1)             // Indexing of vector.
C(i,j)            // C(i+1,j+1)         // Indexing of matrix.

2.2 Resize (reshape in matlab or python) and fill

1
2
MatrixXd A(4, 4) = MatrixXdf:Random(4, 4);  // Giving values.
A.resize(8, 2);                             // Change the dimensions.
1
2
3
4
5
6
7
MaxtrixXd A(3, 3);
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.
MaxtrixXd B(3, 9);
B << A, A, A;     // B is three horizontally stacked A's.
A.fill(11);       // Fill A with all elements of 1.

2.3 Special matrices in Eigen3

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// In Eigen3                        // In 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
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 Blocks of matrix

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// In Eigen3                       // In 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)

2.5 Swaping elements

1
2
3
// In Eigen3                       // In 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 Tranpose

1
2
3
4
5
6
7
8
// Views, transpose, etc; all read-write except for .adjoint().
// In Eigen3                       // In 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)

2.7 Products of Matrices

1
2
3
4
5
6
7
// 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 Element operations

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Vectorized operations on each element independently
// In Eigen3              // In 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)

2.9 Simplifying matrices

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// 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)

2.10 Dot product

1
2
3
4
5
6
// 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 Type convertion

1
2
3
4
5
6
7
8
 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 Linear equation system: $\bf{Ax} = \bf{b}$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// Solve Ax = b. Result stored in x. Matlab: x = A \ b.
x = A.ldlt().solve(b));  // #include <Eigen/Cholesky>LDLT: Inprovement of 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 Eigensystem problems of real matrix

1
2
3
4
5
// In Eigen3                      // In matlab
A.eigenvalues();                  // eig(A);                // Finding eigenvalues.
EigenSolver<Matrix3d> eig(A);     // [vec val] = eig(A);    // Eigensolver.
eig.eigenvalues();                // val                    // Eigenvalues.
eig.eigenvectors();               // vec                    // Eigenvectors.

3. Operations of complex matrix.

3.1 Definitions.

1
2
3
MatrixXcd c(r, c);                  // Declaring a r x c complex matrix.
c.real() << MatrixXd::Random(r, c); // Giving values to the real part.
c.imag() << MatrixXd::Random(r, c); // Giving values to the imaginary part.

3.2 Getting elements, real and imaginary parts.

1
2
3
MatrixXcd array = c.array();
MatrixXd real = c.real();
MatrixXd imag = c.imag();

3.3 Eigensystem problems

1
2
3
4
5
6
MatrixXcd M(r, c);                     // Declaration of a dynamic complex matrix of r x c.
M.real() << MatrixXd::Random(r, c);    // Giving a random matrix to the real part of matrix M.
M.imag() << MatrixXd::Random(r, c);    // Giving a random matrix to the imaginary part of matrix M.
ComplexEigenSolver<MatrixXcd> es(M);   // Complex eigensolver.
MatrixXcd val = es.eigenvalues();      // Finding eigenvalues.
MatrixXcd vec = es.eigenvectors();     // Finding eigen vectors.

Bibliography

https://blog.csdn.net/Zzhouzhou237/article/details/105078647