namespace Eigen { /** \page TutorialCore Tutorial 1/3 - Core features \ingroup Tutorial
\ref index "Overview" | \b Core \b features | \ref TutorialGeometry "Geometry" | \ref TutorialAdvancedLinearAlgebra "Advanced linear algebra"
\b Table \b of \b contents - \ref TutorialCoreGettingStarted - \ref TutorialCoreSimpleExampleFixedSize - \ref TutorialCoreSimpleExampleDynamicSize - \ref TutorialCoreMatrixTypes - \ref TutorialCoreMatrixInitialization - \ref TutorialCoreArithmeticOperators - \ref TutorialCoreReductions - \ref TutorialCoreMatrixBlocks - \ref TutorialCoreDiagonalMatrices - \ref TutorialCoreTransposeAdjoint - \ref TutorialCoreDotNorm - \ref TutorialCoreTriangularMatrix - \ref TutorialLazyEvaluation \n
top\section TutorialCoreGettingStarted Getting started In order to use Eigen, you just need to download and extract Eigen's source code. It is not necessary to use CMake or install anything. Here are some quick compilation instructions with GCC. To quickly test an example program, just do \code g++ -I /path/to/eigen2/ my_program.cpp -o my_program \endcode There is no library to link to. For good performance, add the \c -O2 compile-flag. Note however that this makes it impossible to debug inside Eigen code, as many functions get inlined. In some cases, performance can be further improved by disabling Eigen assertions: use \c -DEIGEN_NO_DEBUG or \c -DNDEBUG to disable them. On the x86 architecture, the SSE2 instruction set is not enabled by default. Use \c -msse2 to enable it, and Eigen will then automatically enable its vectorized paths. On x86-64 and AltiVec-based architectures, vectorization is enabled by default. \section TutorialCoreSimpleExampleFixedSize Simple example with fixed-size matrices and vectors By fixed-size, we mean that the number of rows and columns are fixed at compile-time. In this case, Eigen avoids dynamic memory allocation, and unroll loops when that makes sense. This is useful for very small sizes: typically up to 4x4, sometimes up to 16x16.
\include Tutorial_simple_example_fixed_size.cpp output: \include Tutorial_simple_example_fixed_size.out
top\section TutorialCoreSimpleExampleDynamicSize Simple example with dynamic-size matrices and vectors By dynamic-size, we mean that the numbers of rows and columns are not fixed at compile-time. In this case, they are stored as runtime variables and the arrays are dynamically allocated.
\include Tutorial_simple_example_dynamic_size.cpp output: \include Tutorial_simple_example_dynamic_size.out
top\section TutorialCoreMatrixTypes Matrix and vector types In Eigen, all kinds of dense matrices and vectors are represented by the template class Matrix. In most cases, you can simply use one of the \ref matrixtypedefs "convenience typedefs". The template class Matrix takes a number of template parameters, but for now it is enough to understand the 3 first ones (and the others can then be left unspecified): \code Matrix \endcode \li \c Scalar is the scalar type, i.e. the type of the coefficients. That is, if you want a vector of floats, choose \c float here. \li \c RowsAtCompileTime and \c ColsAtCompileTime are the number of rows and columns of the matrix as known at compile-time. For example, \c Vector3d is a typedef for \code Matrix \endcode For dynamic-size, that is in order to left the number of rows or of columns unspecified at compile-time, use the special value Eigen::Dynamic. For example, \c VectorXd is a typedef for \code Matrix \endcode top\section TutorialCoreMatrixInitialization Matrix and vector creation and initialization \subsection TutorialPredefMat PredefinedMatrix Eigen offers several static methods to create special matrix expressions, and non-static methods to assign these expressions to existing matrices:
Fixed-size matrix or vector Dynamic-size matrix Dynamic-size vector
\code Matrix3f x; x = Matrix3f::Zero(); x = Matrix3f::Ones(); x = Matrix3f::Constant(value); x = Matrix3f::Identity(); x = Matrix3f::Random(); x.setZero(); x.setOnes(); x.setIdentity(); x.setConstant(value); x.setRandom(); \endcode \code MatrixXf x; x = MatrixXf::Zero(rows, cols); x = MatrixXf::Ones(rows, cols); x = MatrixXf::Constant(rows, cols, value); x = MatrixXf::Identity(rows, cols); x = MatrixXf::Random(rows, cols); x.setZero(rows, cols); x.setOnes(rows, cols); x.setConstant(rows, cols, value); x.setIdentity(rows, cols); x.setRandom(rows, cols); \endcode \code VectorXf x; x = VectorXf::Zero(size); x = VectorXf::Ones(size); x = VectorXf::Constant(size, value); x = VectorXf::Identity(size); x = VectorXf::Random(size); x.setZero(size); x.setOnes(size); x.setConstant(size, value); x.setIdentity(size); x.setRandom(size); \endcode
Basis vectors \link MatrixBase::Unit [details]\endlink
\code Vector3f::UnixX() // 1 0 0 Vector3f::UnixY() // 0 1 0 Vector3f::UnixZ() // 0 0 1 \endcode\code VectorXf::Unit(size,i) VectorXf::Unit(4,1) == Vector4f(0,1,0,0) == Vector4f::UnitY() \endcode
Here is an usage example:
\code cout << MatrixXf::Constant(2, 3, sqrt(2)) << endl; RowVector3i v; v.setConstant(6); cout << "v = " << v << endl; \endcode output: \code 1.41 1.41 1.41 1.41 1.41 1.41 v = 6 6 6 \endcode
\subsection TutorialMap Map Any memory buffer can be mapped as an Eigen expression:
\code std::vector stlarray(10); Map(&stlarray[0], stlarray.size()).setOnes(); int data[4] = 1, 2, 3, 4; Matrix2i mat2x2(data); MatrixXi mat2x2 = Map(data); MatrixXi mat2x2 = Map(data,2,2); \endcode
\subsection TutorialCommaInit Comma initializer Eigen also offers a \ref MatrixBaseCommaInitRef "comma initializer syntax" which allows you to set all the coefficients of a matrix to specific values:
\include Tutorial_commainit_01.cpp output: \verbinclude Tutorial_commainit_01.out
Not excited by the above example? Then look at the following one where the matrix is set by blocks:
\include Tutorial_commainit_02.cpp output: \verbinclude Tutorial_commainit_02.out
\b Side \b note: here \link CommaInitializer::finished() .finished() \endlink is used to get the actual matrix object once the comma initialization of our temporary submatrix is done. Note that despite the apparent complexity of such an expression, Eigen's comma initializer usually compiles to very optimized code without any overhead. top\section TutorialCoreArithmeticOperators Arithmetic Operators In short, all arithmetic operators can be used right away as in the following example. Note however that arithmetic operators are only given their usual meaning from mathematics tradition. For other operations, such as taking the coefficient-wise product of two vectors, see the discussion of \link Cwise .cwise() \endlink below. Anyway, here is an example demonstrating basic arithmetic operators: \code mat4 -= mat1*1.5 + mat2 * (mat3/4); \endcode which includes two matrix scalar products ("mat1*1.5" and "mat3/4"), a matrix-matrix product ("mat2 * (mat3/4)"), a matrix addition ("+") and substraction with assignment ("-=").
matrix/vector product\code col2 = mat1 * col1; row2 = row1 * mat1; row1 *= mat1; mat3 = mat1 * mat2; mat3 *= mat1; \endcode
add/subtract\code mat3 = mat1 + mat2; mat3 += mat1; mat3 = mat1 - mat2; mat3 -= mat1;\endcode
scalar product\code mat3 = mat1 * s1; mat3 = s1 * mat1; mat3 *= s1; mat3 = mat1 / s1; mat3 /= s1;\endcode
In Eigen, only traditional mathematical operators can be used right away. But don't worry, thanks to the \link Cwise .cwise() \endlink operator prefix, Eigen's matrices are also very powerful as a numerical container supporting most common coefficient-wise operators:
Coefficient wise \link Cwise::operator*() product \endlink \code mat3 = mat1.cwise() * mat2; \endcode
Add a scalar to all coefficients\code mat3 = mat1.cwise() + scalar; mat3.cwise() += scalar; mat3.cwise() -= scalar; \endcode
Coefficient wise \link Cwise::operator/() division \endlink\code mat3 = mat1.cwise() / mat2; \endcode
Coefficient wise \link Cwise::inverse() reciprocal \endlink\code mat3 = mat1.cwise().inverse(); \endcode
Coefficient wise comparisons \n (support all operators)\code mat3 = mat1.cwise() < mat2; mat3 = mat1.cwise() <= mat2; mat3 = mat1.cwise() > mat2; etc. \endcode
\b Trigo: \n \link Cwise::sin sin \endlink, \link Cwise::cos cos \endlink\code mat3 = mat1.cwise().sin(); etc. \endcode
\b Power: \n \link Cwise::pow() pow \endlink, \link Cwise::square square \endlink, \link Cwise::cube cube \endlink, \n \link Cwise::sqrt sqrt \endlink, \link Cwise::exp exp \endlink, \link Cwise::log log \endlink \code mat3 = mat1.cwise().square(); mat3 = mat1.cwise().pow(5); mat3 = mat1.cwise().log(); etc. \endcode
\link Cwise::min min \endlink, \link Cwise::max max \endlink, \n absolute value (\link Cwise::abs() abs \endlink, \link Cwise::abs2() abs2 \endlink) \code mat3 = mat1.cwise().min(mat2); mat3 = mat1.cwise().max(mat2); mat3 = mat1.cwise().abs(mat2); mat3 = mat1.cwise().abs2(mat2); \endcode
\b Side \b note: If you think that the \c .cwise() syntax is too verbose for your own taste and prefer to have non-conventional mathematical operators directly available, then feel free to extend MatrixBase as described \ref ExtendingMatrixBase "here". So far, we saw the notation \code mat1*mat2 \endcode for matrix product, and \code mat1.cwise()*mat2 \endcode for coefficient-wise product. What about other kinds of products, which in some other libraries also use arithmetic operators? In Eigen, they are accessed as follows -- note that here we are anticipating on further sections, for convenience.
\link MatrixBase::dot() dot product \endlink (inner product)\code scalar = vec1.dot(vec2);\endcode
outer product\code mat = vec1 * vec2.transpose();\endcode
\link MatrixBase::cross() cross product \endlink\code #include vec3 = vec1.cross(vec2);\endcode
top\section TutorialCoreReductions Reductions Eigen provides several reduction methods such as: \link MatrixBase::minCoeff() minCoeff() \endlink, \link MatrixBase::maxCoeff() maxCoeff() \endlink, \link MatrixBase::sum() sum() \endlink, \link MatrixBase::trace() trace() \endlink, \link MatrixBase::norm() norm() \endlink, \link MatrixBase::norm2() norm2() \endlink, \link MatrixBase::all() all() \endlink,and \link MatrixBase::any() any() \endlink. All reduction operations can be done matrix-wise, \link MatrixBase::colwise() column-wise \endlink or \link MatrixBase::rowwise() row-wise \endlink. Usage example:
\code 5 3 1 mat = 2 7 8 9 4 6 \endcode \code mat.minCoeff(); \endcode\code 1 \endcode
\code mat.colwise().minCoeff(); \endcode\code 2 3 1 \endcode
\code mat.rowwise().minCoeff(); \endcode\code 1 2 4 \endcode
Also note that maxCoeff and minCoeff can takes optional arguments returning the coordinates of the respective min/max coeff: \link MatrixBase::maxCoeff(int*,int*) const maxCoeff(int* i, int* j) \endlink, \link MatrixBase::minCoeff(int*,int*) const minCoeff(int* i, int* j) \endlink. \b Side \b note: The all() and any() functions are especially useful in combinaison with coeff-wise comparison operators (\ref CwiseAll "example"). top\section TutorialCoreMatrixBlocks Matrix blocks Read-write access to a \link MatrixBase::col(int) column \endlink or a \link MatrixBase::row(int) row \endlink of a matrix: \code mat1.row(i) = mat2.col(j); mat1.col(j1).swap(mat1.col(j2)); \endcode Read-write access to sub-vectors:
Default versions Optimized versions when the size \n is known at compile time
\code vec1.start(n)\endcode\code vec1.start()\endcodethe first \c n coeffs
\code vec1.end(n)\endcode\code vec1.end()\endcodethe last \c n coeffs
\code vec1.segment(pos,n)\endcode\code vec1.segment(pos)\endcode the \c size coeffs in \n the range [\c pos : \c pos + \c n [
Read-write access to sub-matrices:
\code mat1.block(i,j,rows,cols)\endcode \link MatrixBase::block(int,int,int,int) (more) \endlink \code mat1.block(i,j)\endcode \link MatrixBase::block(int,int) (more) \endlink the \c rows x \c cols sub-matrix \n starting from position (\c i,\c j)
\code mat1.corner(TopLeft,rows,cols) mat1.corner(TopRight,rows,cols) mat1.corner(BottomLeft,rows,cols) mat1.corner(BottomRight,rows,cols)\endcode \link MatrixBase::corner(CornerType,int,int) (more) \endlink \code mat1.corner(TopLeft) mat1.corner(TopRight) mat1.corner(BottomLeft) mat1.corner(BottomRight)\endcode \link MatrixBase::corner(CornerType) (more) \endlink the \c rows x \c cols sub-matrix \n taken in one of the four corners
\code mat4x4.minor(i,j) = mat3x3; mat3x3 = mat4x4.minor(i,j);\endcode \link MatrixBase::minor() minor \endlink (read-write)
top\section TutorialCoreDiagonalMatrices Diagonal matrices
\link MatrixBase::asDiagonal() make a diagonal matrix \endlink from a vector \n this product is automatically optimized !\code mat3 = mat1 * vec2.asDiagonal();\endcode
Access \link MatrixBase::diagonal() the diagonal of a matrix \endlink as a vector (read/write) \code vec1 = mat1.diagonal(); mat1.diagonal() = vec1; \endcode
top\section TutorialCoreTransposeAdjoint Transpose and Adjoint operations
\link MatrixBase::transpose() transposition \endlink (read-write)\code mat3 = mat1.transpose() * mat2; mat3.transpose() = mat1 * mat2.transpose(); \endcode
\link MatrixBase::adjoint() adjoint \endlink (read only)\n\code mat3 = mat1.adjoint() * mat2; \endcode
top\section TutorialCoreDotNorm Dot-product, vector norm, normalization
\link MatrixBase::dot() Dot-product \endlink of two vectors \code vec1.dot(vec2);\endcode
\link MatrixBase::norm() norm \endlink of a vector \n \link MatrixBase::norm2() squared norm \endlink of a vector \code vec.norm(); \endcode \n \code vec.norm2() \endcode
returns a \link MatrixBase::normalized() normalized \endlink vector \n \link MatrixBase::normalize() normalize \endlink a vector \code vec3 = vec1.normalized(); vec1.normalize();\endcode
top\section TutorialCoreTriangularMatrix Dealing with triangular matrices todo top\section TutorialLazyEvaluation Lazy evaluation of expressions When you write a line of code involving a complex expression such as \code mat1 = mat2 + mat3 * (mat4 + mat5); \endcode Eigen determines automatically, for each sub-expression, whether to evaluate it into a temporary variable. Indeed, in certain cases it is better to evaluate immediately a sub-expression into a temporary variable, while in other cases it is better to avoid that. A traditional math library without expression templates always evaluates all sub-expressions into temporaries. So with this code, \code vec1 = vec2 + vec3; \endcode a traditional library would evaluate \c vec2 + vec3 into a temporary \c vec4 and then copy \c vec4 into \c vec1. This is of course inefficient: the arrays are traversed twice, so there are a lot of useless load/store operations. Expression-templates-based libraries can avoid evaluating sub-expressions into temporaries, which in many cases results in large speed improvements. This is called lazy evaluation as an expression is getting evaluated as late as possible, instead of immediately. However, most other expression-templates-based libraries always choose lazy evaluation. There are two problems with that: first, lazy evaluation is not always a good choice for performance; second, lazy evaluation can be very dangerous, for example with matrix products: doing matrix = matrix*matrix gives a wrong result if the matrix product is lazy-evaluated, because of the way matrix product works. For these reasons, Eigen has intelligent compile-time mechanisms to determine automatically when to use lazy evaluation, and when on the contrary it should evaluate immediately into a temporary variable. So in the basic example, \code matrix1 = matrix2 + matrix3; \endcode Eigen chooses lazy evaluation. Thus the arrays are traversed only once, producing optimized code. If you really want to force immediate evaluation, use \link MatrixBase::eval() eval() \endlink: \code matrix1 = (matrix2 + matrix3).eval(); \endcode Here is now a more involved example: \code matrix1 = -matrix2 + matrix3 + 5 * matrix4; \endcode Eigen chooses lazy evaluation at every stage in that example, which is clearly the correct choice. In fact, lazy evaluation is the "default choice" and Eigen will choose it except in a few circumstances. The first circumstance in which Eigen chooses immediate evaluation, is when it sees an assignment a = b; and the expression \c b has the evaluate-before-assigning \link flags flag \endlink. The most importat example of such an expression is the \link Product matrix product expression \endlink. For example, when you do \code matrix = matrix * matrix; \endcode Eigen first evaluates matrix * matrix into a temporary matrix, and then copies it into the original \c matrix. This guarantees a correct result as we saw above that lazy evaluation gives wrong results with matrix products. It also doesn't cost much, as the cost of the matrix product itself is much higher. What if you know what you are doing and want to force lazy evaluation? Then use \link MatrixBase::lazy() .lazy() \endlink instead. Here is an example: \code matrix1 = (matrix2 * matrix2).lazy(); \endcode Here, since we know that matrix2 is not the same matrix as matrix1, we know that lazy evaluation is not dangerous, so we may force lazy evaluation. Concretely, the effect of lazy() here is to remove the evaluate-before-assigning \link flags flag \endlink and also the evaluate-before-nesting \link flags flag \endlink which we now discuss. The second circumstance in which Eigen chooses immediate evaluation, is when it sees a nested expression such as a + b where \c b is already an expression having the evaluate-before-nesting \link flags flag \endlink. Again, the most importat example of such an expression is the \link Product matrix product expression \endlink. For example, when you do \code matrix1 = matrix2 + matrix3 * matrix4; \endcode the product matrix3 * matrix4 gets evaluated immediately into a temporary matrix. Indeed, experiments showed that it is often beneficial for performance to evaluate immediately matrix products when they are nested into bigger expressions. Again, \link MatrixBase::lazy() .lazy() \endlink can be used to force lazy evaluation here. The third circumstance in which Eigen chooses immediate evaluation, is when its cost model shows that the total cost of an operation is reduced if a sub-expression gets evaluated into a temporary. Indeed, in certain cases, an intermediate result is sufficiently costly to compute and is reused sufficiently many times, that is worth "caching". Here is an example: \code matrix1 = matrix2 * (matrix3 + matrix4); \endcode Here, provided the matrices have at least 2 rows and 2 columns, each coefficienct of the expression matrix3 + matrix4 is going to be used several times in the matrix product. Instead of computing the sum everytime, it is much better to compute it once and store it in a temporary variable. Eigen understands this and evaluates matrix3 + matrix4 into a temporary variable before evaluating the product. */ }