• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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// Eigen                           // Matlab
54x.head(n)                          // x(1:n)
55x.head<n>()                        // x(1:n)
56x.tail(n)                          // x(end - n + 1: end)
57x.tail<n>()                        // x(end - n + 1: end)
58x.segment(i, n)                    // x(i+1 : i+n)
59x.segment<n>(i)                    // x(i+1 : i+n)
60P.block(i, j, rows, cols)          // P(i+1 : i+rows, j+1 : j+cols)
61P.block<rows, cols>(i, j)          // P(i+1 : i+rows, j+1 : j+cols)
62P.row(i)                           // P(i+1, :)
63P.col(j)                           // P(:, j+1)
64P.leftCols<cols>()                 // P(:, 1:cols)
65P.leftCols(cols)                   // P(:, 1:cols)
66P.middleCols<cols>(j)              // P(:, j+1:j+cols)
67P.middleCols(j, cols)              // P(:, j+1:j+cols)
68P.rightCols<cols>()                // P(:, end-cols+1:end)
69P.rightCols(cols)                  // P(:, end-cols+1:end)
70P.topRows<rows>()                  // P(1:rows, :)
71P.topRows(rows)                    // P(1:rows, :)
72P.middleRows<rows>(i)              // P(i+1:i+rows, :)
73P.middleRows(i, rows)              // P(i+1:i+rows, :)
74P.bottomRows<rows>()               // P(end-rows+1:end, :)
75P.bottomRows(rows)                 // P(end-rows+1:end, :)
76P.topLeftCorner(rows, cols)        // P(1:rows, 1:cols)
77P.topRightCorner(rows, cols)       // P(1:rows, end-cols+1:end)
78P.bottomLeftCorner(rows, cols)     // P(end-rows+1:end, 1:cols)
79P.bottomRightCorner(rows, cols)    // P(end-rows+1:end, end-cols+1:end)
80P.topLeftCorner<rows,cols>()       // P(1:rows, 1:cols)
81P.topRightCorner<rows,cols>()      // P(1:rows, end-cols+1:end)
82P.bottomLeftCorner<rows,cols>()    // P(end-rows+1:end, 1:cols)
83P.bottomRightCorner<rows,cols>()   // P(end-rows+1:end, end-cols+1:end)
84
85// Of particular note is Eigen's swap function which is highly optimized.
86// Eigen                           // Matlab
87R.row(i) = P.col(j);               // R(i, :) = P(:, j)
88R.col(j1).swap(mat1.col(j2));      // R(:, [j1 j2]) = R(:, [j2, j1])
89
90// Views, transpose, etc;
91// Eigen                           // Matlab
92R.adjoint()                        // R'
93R.transpose()                      // R.' or conj(R')       // Read-write
94R.diagonal()                       // diag(R)               // Read-write
95x.asDiagonal()                     // diag(x)
96R.transpose().colwise().reverse()  // rot90(R)              // Read-write
97R.rowwise().reverse()              // fliplr(R)
98R.colwise().reverse()              // flipud(R)
99R.replicate(i,j)                   // repmat(P,i,j)
100
101
102// All the same as Matlab, but matlab doesn't have *= style operators.
103// Matrix-vector.  Matrix-matrix.   Matrix-scalar.
104y  = M*x;          R  = P*Q;        R  = P*s;
105a  = b*M;          R  = P - Q;      R  = s*P;
106a *= M;            R  = P + Q;      R  = P/s;
107                   R *= Q;          R  = s*P;
108                   R += Q;          R *= s;
109                   R -= Q;          R /= s;
110
111// Vectorized operations on each element independently
112// Eigen                       // Matlab
113R = P.cwiseProduct(Q);         // R = P .* Q
114R = P.array() * s.array();     // R = P .* s
115R = P.cwiseQuotient(Q);        // R = P ./ Q
116R = P.array() / Q.array();     // R = P ./ Q
117R = P.array() + s.array();     // R = P + s
118R = P.array() - s.array();     // R = P - s
119R.array() += s;                // R = R + s
120R.array() -= s;                // R = R - s
121R.array() < Q.array();         // R < Q
122R.array() <= Q.array();        // R <= Q
123R.cwiseInverse();              // 1 ./ P
124R.array().inverse();           // 1 ./ P
125R.array().sin()                // sin(P)
126R.array().cos()                // cos(P)
127R.array().pow(s)               // P .^ s
128R.array().square()             // P .^ 2
129R.array().cube()               // P .^ 3
130R.cwiseSqrt()                  // sqrt(P)
131R.array().sqrt()               // sqrt(P)
132R.array().exp()                // exp(P)
133R.array().log()                // log(P)
134R.cwiseMax(P)                  // max(R, P)
135R.array().max(P.array())       // max(R, P)
136R.cwiseMin(P)                  // min(R, P)
137R.array().min(P.array())       // min(R, P)
138R.cwiseAbs()                   // abs(P)
139R.array().abs()                // abs(P)
140R.cwiseAbs2()                  // abs(P.^2)
141R.array().abs2()               // abs(P.^2)
142(R.array() < s).select(P,Q );  // (R < s ? P : Q)
143R = (Q.array()==0).select(P,R) // R(Q==0) = P(Q==0)
144R = P.unaryExpr(ptr_fun(func)) // R = arrayfun(func, P)   // with: scalar func(const scalar &x);
145
146
147// Reductions.
148int r, c;
149// Eigen                  // Matlab
150R.minCoeff()              // min(R(:))
151R.maxCoeff()              // max(R(:))
152s = R.minCoeff(&r, &c)    // [s, i] = min(R(:)); [r, c] = ind2sub(size(R), i);
153s = R.maxCoeff(&r, &c)    // [s, i] = max(R(:)); [r, c] = ind2sub(size(R), i);
154R.sum()                   // sum(R(:))
155R.colwise().sum()         // sum(R)
156R.rowwise().sum()         // sum(R, 2) or sum(R')'
157R.prod()                  // prod(R(:))
158R.colwise().prod()        // prod(R)
159R.rowwise().prod()        // prod(R, 2) or prod(R')'
160R.trace()                 // trace(R)
161R.all()                   // all(R(:))
162R.colwise().all()         // all(R)
163R.rowwise().all()         // all(R, 2)
164R.any()                   // any(R(:))
165R.colwise().any()         // any(R)
166R.rowwise().any()         // any(R, 2)
167
168// Dot products, norms, etc.
169// Eigen                  // Matlab
170x.norm()                  // norm(x).    Note that norm(R) doesn't work in Eigen.
171x.squaredNorm()           // dot(x, x)   Note the equivalence is not true for complex
172x.dot(y)                  // dot(x, y)
173x.cross(y)                // cross(x, y) Requires #include <Eigen/Geometry>
174
175//// Type conversion
176// Eigen                  // Matlab
177A.cast<double>();         // double(A)
178A.cast<float>();          // single(A)
179A.cast<int>();            // int32(A)
180A.real();                 // real(A)
181A.imag();                 // imag(A)
182// if the original type equals destination type, no work is done
183
184// Note that for most operations Eigen requires all operands to have the same type:
185MatrixXf F = MatrixXf::Zero(3,3);
186A += F;                // illegal in Eigen. In Matlab A = A+F is allowed
187A += F.cast<double>(); // F converted to double and then added (generally, conversion happens on-the-fly)
188
189// Eigen can map existing memory into Eigen matrices.
190float array[3];
191Vector3f::Map(array).fill(10);            // create a temporary Map over array and sets entries to 10
192int data[4] = {1, 2, 3, 4};
193Matrix2i mat2x2(data);                    // copies data into mat2x2
194Matrix2i::Map(data) = 2*mat2x2;           // overwrite elements of data with 2*mat2x2
195MatrixXi::Map(data, 2, 2) += mat2x2;      // adds mat2x2 to elements of data (alternative syntax if size is not know at compile time)
196
197// Solve Ax = b. Result stored in x. Matlab: x = A \ b.
198x = A.ldlt().solve(b));  // A sym. p.s.d.    #include <Eigen/Cholesky>
199x = A.llt() .solve(b));  // A sym. p.d.      #include <Eigen/Cholesky>
200x = A.lu()  .solve(b));  // Stable and fast. #include <Eigen/LU>
201x = A.qr()  .solve(b));  // No pivoting.     #include <Eigen/QR>
202x = A.svd() .solve(b));  // Stable, slowest. #include <Eigen/SVD>
203// .ldlt() -> .matrixL() and .matrixD()
204// .llt()  -> .matrixL()
205// .lu()   -> .matrixL() and .matrixU()
206// .qr()   -> .matrixQ() and .matrixR()
207// .svd()  -> .matrixU(), .singularValues(), and .matrixV()
208
209// Eigenvalue problems
210// Eigen                          // Matlab
211A.eigenvalues();                  // eig(A);
212EigenSolver<Matrix3d> eig(A);     // [vec val] = eig(A)
213eig.eigenvalues();                // diag(val)
214eig.eigenvectors();               // vec
215// For self-adjoint matrices use SelfAdjointEigenSolver<>
216