1// A simple quickref for Eigen. Add anything that's missing. 2// Main author: Keir Mierle 3 4#include <Eigen/Dense> 5 6Matrix<double, 3, 3> A; // Fixed rows and cols. Same as Matrix3d. 7Matrix<double, 3, Dynamic> B; // Fixed rows, dynamic cols. 8Matrix<double, Dynamic, Dynamic> C; // Full dynamic. Same as MatrixXd. 9Matrix<double, 3, 3, RowMajor> E; // Row major; default is column-major. 10Matrix3f P, Q, R; // 3x3 float matrix. 11Vector3f x, y, z; // 3x1 float matrix. 12RowVector3f a, b, c; // 1x3 float matrix. 13VectorXd v; // Dynamic column vector of doubles 14double s; 15 16// Basic usage 17// Eigen // Matlab // comments 18x.size() // length(x) // vector size 19C.rows() // size(C,1) // number of rows 20C.cols() // size(C,2) // number of columns 21x(i) // x(i+1) // Matlab is 1-based 22C(i,j) // C(i+1,j+1) // 23 24A.resize(4, 4); // Runtime error if assertions are on. 25B.resize(4, 9); // Runtime error if assertions are on. 26A.resize(3, 3); // Ok; size didn't change. 27B.resize(3, 9); // Ok; only dynamic cols changed. 28 29A << 1, 2, 3, // Initialize A. The elements can also be 30 4, 5, 6, // matrices, which are stacked along cols 31 7, 8, 9; // and then the rows are stacked. 32B << A, A, A; // B is three horizontally stacked A's. 33A.fill(10); // Fill A with all 10's. 34 35// Eigen // Matlab 36MatrixXd::Identity(rows,cols) // eye(rows,cols) 37C.setIdentity(rows,cols) // C = eye(rows,cols) 38MatrixXd::Zero(rows,cols) // zeros(rows,cols) 39C.setZero(rows,cols) // C = zeros(rows,cols) 40MatrixXd::Ones(rows,cols) // ones(rows,cols) 41C.setOnes(rows,cols) // C = ones(rows,cols) 42MatrixXd::Random(rows,cols) // rand(rows,cols)*2-1 // MatrixXd::Random returns uniform random numbers in (-1, 1). 43C.setRandom(rows,cols) // C = rand(rows,cols)*2-1 44VectorXd::LinSpaced(size,low,high) // linspace(low,high,size)' 45v.setLinSpaced(size,low,high) // v = linspace(low,high,size)' 46VectorXi::LinSpaced(((hi-low)/step)+1, // low:step:hi 47 low,low+step*(size-1)) // 48 49 50// Matrix slicing and blocks. All expressions listed here are read/write. 51// Templated size versions are faster. Note that Matlab is 1-based (a size N 52// vector is x(1)...x(N)). 53/******************************************************************************/ 54/* PLEASE HELP US IMPROVING THIS SECTION */ 55/* Eigen 3.4 supports a much improved API for sub-matrices, including, */ 56/* slicing and indexing from arrays: */ 57/* http://eigen.tuxfamily.org/dox-devel/group__TutorialSlicingIndexing.html */ 58/******************************************************************************/ 59// Eigen // Matlab 60x.head(n) // x(1:n) 61x.head<n>() // x(1:n) 62x.tail(n) // x(end - n + 1: end) 63x.tail<n>() // x(end - n + 1: end) 64x.segment(i, n) // x(i+1 : i+n) 65x.segment<n>(i) // x(i+1 : i+n) 66P.block(i, j, rows, cols) // P(i+1 : i+rows, j+1 : j+cols) 67P.block<rows, cols>(i, j) // P(i+1 : i+rows, j+1 : j+cols) 68P.row(i) // P(i+1, :) 69P.col(j) // P(:, j+1) 70P.leftCols<cols>() // P(:, 1:cols) 71P.leftCols(cols) // P(:, 1:cols) 72P.middleCols<cols>(j) // P(:, j+1:j+cols) 73P.middleCols(j, cols) // P(:, j+1:j+cols) 74P.rightCols<cols>() // P(:, end-cols+1:end) 75P.rightCols(cols) // P(:, end-cols+1:end) 76P.topRows<rows>() // P(1:rows, :) 77P.topRows(rows) // P(1:rows, :) 78P.middleRows<rows>(i) // P(i+1:i+rows, :) 79P.middleRows(i, rows) // P(i+1:i+rows, :) 80P.bottomRows<rows>() // P(end-rows+1:end, :) 81P.bottomRows(rows) // P(end-rows+1:end, :) 82P.topLeftCorner(rows, cols) // P(1:rows, 1:cols) 83P.topRightCorner(rows, cols) // P(1:rows, end-cols+1:end) 84P.bottomLeftCorner(rows, cols) // P(end-rows+1:end, 1:cols) 85P.bottomRightCorner(rows, cols) // P(end-rows+1:end, end-cols+1:end) 86P.topLeftCorner<rows,cols>() // P(1:rows, 1:cols) 87P.topRightCorner<rows,cols>() // P(1:rows, end-cols+1:end) 88P.bottomLeftCorner<rows,cols>() // P(end-rows+1:end, 1:cols) 89P.bottomRightCorner<rows,cols>() // P(end-rows+1:end, end-cols+1:end) 90 91// Of particular note is Eigen's swap function which is highly optimized. 92// Eigen // Matlab 93R.row(i) = P.col(j); // R(i, :) = P(:, j) 94R.col(j1).swap(mat1.col(j2)); // R(:, [j1 j2]) = R(:, [j2, j1]) 95 96// Views, transpose, etc; 97/******************************************************************************/ 98/* PLEASE HELP US IMPROVING THIS SECTION */ 99/* Eigen 3.4 supports a new API for reshaping: */ 100/* http://eigen.tuxfamily.org/dox-devel/group__TutorialReshape.html */ 101/******************************************************************************/ 102// Eigen // Matlab 103R.adjoint() // R' 104R.transpose() // R.' or conj(R') // Read-write 105R.diagonal() // diag(R) // Read-write 106x.asDiagonal() // diag(x) 107R.transpose().colwise().reverse() // rot90(R) // Read-write 108R.rowwise().reverse() // fliplr(R) 109R.colwise().reverse() // flipud(R) 110R.replicate(i,j) // repmat(P,i,j) 111 112 113// All the same as Matlab, but matlab doesn't have *= style operators. 114// Matrix-vector. Matrix-matrix. Matrix-scalar. 115y = M*x; R = P*Q; R = P*s; 116a = b*M; R = P - Q; R = s*P; 117a *= M; R = P + Q; R = P/s; 118 R *= Q; R = s*P; 119 R += Q; R *= s; 120 R -= Q; R /= s; 121 122// Vectorized operations on each element independently 123// Eigen // Matlab 124R = P.cwiseProduct(Q); // R = P .* Q 125R = P.array() * s.array(); // R = P .* s 126R = P.cwiseQuotient(Q); // R = P ./ Q 127R = P.array() / Q.array(); // R = P ./ Q 128R = P.array() + s.array(); // R = P + s 129R = P.array() - s.array(); // R = P - s 130R.array() += s; // R = R + s 131R.array() -= s; // R = R - s 132R.array() < Q.array(); // R < Q 133R.array() <= Q.array(); // R <= Q 134R.cwiseInverse(); // 1 ./ P 135R.array().inverse(); // 1 ./ P 136R.array().sin() // sin(P) 137R.array().cos() // cos(P) 138R.array().pow(s) // P .^ s 139R.array().square() // P .^ 2 140R.array().cube() // P .^ 3 141R.cwiseSqrt() // sqrt(P) 142R.array().sqrt() // sqrt(P) 143R.array().exp() // exp(P) 144R.array().log() // log(P) 145R.cwiseMax(P) // max(R, P) 146R.array().max(P.array()) // max(R, P) 147R.cwiseMin(P) // min(R, P) 148R.array().min(P.array()) // min(R, P) 149R.cwiseAbs() // abs(P) 150R.array().abs() // abs(P) 151R.cwiseAbs2() // abs(P.^2) 152R.array().abs2() // abs(P.^2) 153(R.array() < s).select(P,Q ); // (R < s ? P : Q) 154R = (Q.array()==0).select(P,R) // R(Q==0) = P(Q==0) 155R = P.unaryExpr(ptr_fun(func)) // R = arrayfun(func, P) // with: scalar func(const scalar &x); 156 157 158// Reductions. 159int r, c; 160// Eigen // Matlab 161R.minCoeff() // min(R(:)) 162R.maxCoeff() // max(R(:)) 163s = R.minCoeff(&r, &c) // [s, i] = min(R(:)); [r, c] = ind2sub(size(R), i); 164s = R.maxCoeff(&r, &c) // [s, i] = max(R(:)); [r, c] = ind2sub(size(R), i); 165R.sum() // sum(R(:)) 166R.colwise().sum() // sum(R) 167R.rowwise().sum() // sum(R, 2) or sum(R')' 168R.prod() // prod(R(:)) 169R.colwise().prod() // prod(R) 170R.rowwise().prod() // prod(R, 2) or prod(R')' 171R.trace() // trace(R) 172R.all() // all(R(:)) 173R.colwise().all() // all(R) 174R.rowwise().all() // all(R, 2) 175R.any() // any(R(:)) 176R.colwise().any() // any(R) 177R.rowwise().any() // any(R, 2) 178 179// Dot products, norms, etc. 180// Eigen // Matlab 181x.norm() // norm(x). Note that norm(R) doesn't work in Eigen. 182x.squaredNorm() // dot(x, x) Note the equivalence is not true for complex 183x.dot(y) // dot(x, y) 184x.cross(y) // cross(x, y) Requires #include <Eigen/Geometry> 185 186//// Type conversion 187// Eigen // Matlab 188A.cast<double>(); // double(A) 189A.cast<float>(); // single(A) 190A.cast<int>(); // int32(A) 191A.real(); // real(A) 192A.imag(); // imag(A) 193// if the original type equals destination type, no work is done 194 195// Note that for most operations Eigen requires all operands to have the same type: 196MatrixXf F = MatrixXf::Zero(3,3); 197A += F; // illegal in Eigen. In Matlab A = A+F is allowed 198A += F.cast<double>(); // F converted to double and then added (generally, conversion happens on-the-fly) 199 200// Eigen can map existing memory into Eigen matrices. 201float array[3]; 202Vector3f::Map(array).fill(10); // create a temporary Map over array and sets entries to 10 203int data[4] = {1, 2, 3, 4}; 204Matrix2i mat2x2(data); // copies data into mat2x2 205Matrix2i::Map(data) = 2*mat2x2; // overwrite elements of data with 2*mat2x2 206MatrixXi::Map(data, 2, 2) += mat2x2; // adds mat2x2 to elements of data (alternative syntax if size is not know at compile time) 207 208// Solve Ax = b. Result stored in x. Matlab: x = A \ b. 209x = A.ldlt().solve(b)); // A sym. p.s.d. #include <Eigen/Cholesky> 210x = A.llt() .solve(b)); // A sym. p.d. #include <Eigen/Cholesky> 211x = A.lu() .solve(b)); // Stable and fast. #include <Eigen/LU> 212x = A.qr() .solve(b)); // No pivoting. #include <Eigen/QR> 213x = A.svd() .solve(b)); // Stable, slowest. #include <Eigen/SVD> 214// .ldlt() -> .matrixL() and .matrixD() 215// .llt() -> .matrixL() 216// .lu() -> .matrixL() and .matrixU() 217// .qr() -> .matrixQ() and .matrixR() 218// .svd() -> .matrixU(), .singularValues(), and .matrixV() 219 220// Eigenvalue problems 221// Eigen // Matlab 222A.eigenvalues(); // eig(A); 223EigenSolver<Matrix3d> eig(A); // [vec val] = eig(A) 224eig.eigenvalues(); // diag(val) 225eig.eigenvectors(); // vec 226// For self-adjoint matrices use SelfAdjointEigenSolver<> 227