blob: 55aab961e8fae23216ecd9114eb110258d664da1 [file] [log] [blame]
Carlos Becker9d440052010-06-25 20:16:12 -04001namespace Eigen {
2
Benoit Jacobe078bb22010-06-26 14:00:00 -04003/** \page TutorialMatrixArithmetic Tutorial page 2 - %Matrix and vector arithmetic
Carlos Becker9d440052010-06-25 20:16:12 -04004 \ingroup Tutorial
5
Benoit Jacobe078bb22010-06-26 14:00:00 -04006\li \b Previous: \ref TutorialMatrixClass
7\li \b Next: \ref TutorialArrayClass
8
9This tutorial aims to provide an overview and some details on how to perform arithmetic
10between matrices, vectors and scalars with Eigen.
Carlos Becker9d440052010-06-25 20:16:12 -040011
12\b Table \b of \b contents
Benoit Jacobe078bb22010-06-26 14:00:00 -040013 - \ref TutorialArithmeticIntroduction
Benoit Jacobe078bb22010-06-26 14:00:00 -040014 - \ref TutorialArithmeticAddSub
15 - \ref TutorialArithmeticScalarMulDiv
16 - \ref TutorialArithmeticMentionXprTemplates
Gael Guennebaudde1220a2010-06-28 00:05:11 +020017 - \ref TutorialArithmeticTranspose
Benoit Jacobe078bb22010-06-26 14:00:00 -040018 - \ref TutorialArithmeticMatrixMul
19 - \ref TutorialArithmeticDotAndCross
20 - \ref TutorialArithmeticRedux
21 - \ref TutorialArithmeticValidity
Carlos Becker9d440052010-06-25 20:16:12 -040022
Benoit Jacobe078bb22010-06-26 14:00:00 -040023\section TutorialArithmeticIntroduction Introduction
Carlos Becker9d440052010-06-25 20:16:12 -040024
Benoit Jacobe078bb22010-06-26 14:00:00 -040025Eigen offers matrix/vector arithmetic operations either through overloads of common C++ arithmetic operators such as +, -, *,
26or through special methods such as dot(), cross(), etc.
27For the Matrix class (matrices and vectors), operators are only overloaded to support
28linear-algebraic operations. For example, \c matrix1 \c * \c matrix2 means matrix-matrix product,
29and \c vector \c + \c scalar is just not allowed. If you want to perform all kinds of array operations,
30not linear algebra, see \ref TutorialArrayClass "next page".
31
Benoit Jacobe078bb22010-06-26 14:00:00 -040032\section TutorialArithmeticAddSub Addition and substraction
33
34The left hand side and right hand side must, of course, have the same numbers of rows and of columns. They must
35also have the same \c Scalar type, as Eigen doesn't do automatic type promotion. The operators at hand here are:
36\li binary operator + as in \c a+b
37\li binary operator - as in \c a-b
38\li unary operator - as in \c -a
39\li compound operator += as in \c a+=b
40\li compound operator -= as in \c a-=b
41
42Example: \include tut_arithmetic_add_sub.cpp
43Output: \verbinclude tut_arithmetic_add_sub.out
44
45\section TutorialArithmeticScalarMulDiv Scalar multiplication and division
46
47Multiplication and division by a scalar is very simple too. The operators at hand here are:
48\li binary operator * as in \c matrix*scalar
49\li binary operator * as in \c scalar*matrix
50\li binary operator / as in \c matrix/scalar
51\li compound operator *= as in \c matrix*=scalar
52\li compound operator /= as in \c matrix/=scalar
53
54Example: \include tut_arithmetic_scalar_mul_div.cpp
55Output: \verbinclude tut_arithmetic_scalar_mul_div.out
56
57\section TutorialArithmeticMentionXprTemplates A note about expression templates
58
59This is an advanced topic that we explain in \ref TopicEigenExpressionTemplates "this page",
60but it is useful to just mention it now. In Eigen, arithmetic operators such as \c operator+ don't
61perform any computation by themselves, they just return an "expression object" describing the computation to be
62performed. The actual computation happens later, when the whole expression is evaluated, typically in \c operator=.
63While this might sound heavy, any modern optimizing compiler is able to optimize away that abstraction and
64the result is perfectly optimized code. For example, when you do:
Carlos Becker9d440052010-06-25 20:16:12 -040065\code
Benoit Jacobe078bb22010-06-26 14:00:00 -040066VectorXf a(50), b(50), c(50), d(50);
67...
68a = 3*b + 4*c + 5*d;
Carlos Becker9d440052010-06-25 20:16:12 -040069\endcode
Benoit Jacobe078bb22010-06-26 14:00:00 -040070Eigen compiles it to just one for loop, so that the arrays are traversed only once. Simplyfying (e.g. ignoring
71SIMD optimizations), this loop looks like this:
Carlos Becker9d440052010-06-25 20:16:12 -040072\code
Benoit Jacobe078bb22010-06-26 14:00:00 -040073for(int i = 0; i < 50; ++i)
74 a[i] = 3*b[i] + 4*c[i] + 5*d[i];
Carlos Becker9d440052010-06-25 20:16:12 -040075\endcode
Benoit Jacobe078bb22010-06-26 14:00:00 -040076Thus, you should not be afraid of using relatively large arithmetic expressions with Eigen: it only gives Eigen
77more opportunities for optimization.
78
Gael Guennebaudde1220a2010-06-28 00:05:11 +020079\section TutorialArithmeticTranspose Transposition and conjugation
80
81The \c transpose \f$ a^T \f$, \c conjugate \f$ \bar{a} \f$, and the \c adjoint (i.e., conjugate transpose) of the matrix or vector \f$ a \f$, are simply obtained by the functions of the same names.
82
83<table class="tutorial_code"><tr><td>
84Example: \include tut_arithmetic_transpose_conjugate.cpp
85</td>
86<td>
87Output: \include tut_arithmetic_transpose_conjugate.out
88</td></tr></table>
89
90For real matrices, \c conjugate() is a no-operation, and so \c adjoint() is 100% equivalent to \c transpose().
91
92As for basic arithmetic operators, \c transpose and \c adjoint simply return a proxy object without doing the actual transposition. Therefore, <tt>a=a.transpose()</tt> leads to an unexpected result:
93<table class="tutorial_code"><tr><td>
94Example: \include tut_arithmetic_transpose_aliasing.cpp
95</td>
96<td>
97Output: \include tut_arithmetic_transpose_aliasing.out
98</td></tr></table>
99In "debug mode", i.e., when assertions have not been disabled, such common pitfalls are automatically detected. For \em in-place transposition, simply use the transposeInPlace() function:
100<table class="tutorial_code"><tr><td>
101Example: \include tut_arithmetic_transpose_inplace.cpp
102</td>
103<td>
104Output: \include tut_arithmetic_transpose_inplace.out
105</td></tr></table>
106There is also the adjointInPlace() function for complex matrix.
107
Benoit Jacobe078bb22010-06-26 14:00:00 -0400108\section TutorialArithmeticMatrixMul Matrix-matrix and matrix-vector multiplication
109
110Matrix-matrix multiplication is again done with \c operator*. Since vectors are a special
111case of matrices, they are implicitly handled there too, so matrix-vector product is really just a special
112case of matrix-matrix product, and so is vector-vector outer product. Thus, all these cases are handled by just
113two operators:
114\li binary operator * as in \c a*b
115\li compound operator *= as in \c a*=b
116
117Example: \include tut_arithmetic_matrix_mul.cpp
118Output: \verbinclude tut_arithmetic_matrix_mul.out
119
120Note: if you read the above paragraph on expression templates and are worried that doing \c m=m*m might cause
121aliasing issues, be reassured for now: Eigen treats matrix multiplication as a special case and takes care of
122introducing a temporary here, so it will compile \c m=m*m as:
Carlos Becker9d440052010-06-25 20:16:12 -0400123\code
Benoit Jacobe078bb22010-06-26 14:00:00 -0400124tmp = m*m;
125m = tmp;
Carlos Becker9d440052010-06-25 20:16:12 -0400126\endcode
Gael Guennebaud75da2542010-06-28 00:42:57 +0200127If you know your matrix product can be safely evluated into the destination matrix without aliasing issue, then you can use the \c nolias() function to avoid the temporary, e.g.:
128\code
129c.noalias() += a * b;
130\endcode
Benoit Jacobe078bb22010-06-26 14:00:00 -0400131For more details on this topic, see \ref TopicEigenExpressionTemplates "this page".
Carlos Becker9d440052010-06-25 20:16:12 -0400132
Gael Guennebaud75da2542010-06-28 00:42:57 +0200133\b Note: for BLAS users worried about performance, expressions such as <tt>c.noalias() -= 2 * a.adjoint() * b;</tt> are fully optimized and trigger a single gemm-like function call.
134
Benoit Jacobe078bb22010-06-26 14:00:00 -0400135\section TutorialArithmeticDotAndCross Dot product and cross product
Carlos Becker9d440052010-06-25 20:16:12 -0400136
Benoit Jacobe078bb22010-06-26 14:00:00 -0400137The above-discussed \c operator* does not allow to compute dot and cross products. For that, you need the dot() and cross() methods.
138Example: \include tut_arithmetic_dot_cross.cpp
139Output: \verbinclude tut_arithmetic_dot_cross.out
Carlos Becker9d440052010-06-25 20:16:12 -0400140
Benoit Jacobe078bb22010-06-26 14:00:00 -0400141Remember that cross product is only for vectors of size 3. Dot product is for vectors of any sizes.
142When using complex numbers, Eigen's dot product is conjugate-linear in the first variable and linear in the
143second variable.
Carlos Becker9d440052010-06-25 20:16:12 -0400144
Benoit Jacobe078bb22010-06-26 14:00:00 -0400145\section TutorialArithmeticRedux Basic arithmetic reduction operations
146Eigen also provides some reduction operations to obtain values such as the sum or the maximum
147or minimum of all the coefficients in a given matrix or vector.
Carlos Becker9d440052010-06-25 20:16:12 -0400148
Benoit Jacobe078bb22010-06-26 14:00:00 -0400149TODO: convert this from table format to tutorial/examples format.
Carlos Becker9d440052010-06-25 20:16:12 -0400150
151<table class="tutorial_code" align="center">
152<tr><td align="center">\b Reduction \b operation</td><td align="center">\b Usage \b example</td></tr>
153<tr><td>
154Sum of all the coefficients in a matrix</td><td>\code
155MatrixXf m;
156float totalSum = m.sum();\endcode</td></tr>
157<tr><td>
158Maximum coefficient in a matrix</td><td>\code
159MatrixXf m;
160int row, col;
161
162// minimum value will be stored in minValue
163// and the row and column where it was found in row and col,
164// (these two parameters are optional)
165float minValue = m.minCoeff(&row,&col);\endcode</td></tr>
166<tr><td>
167Maximum coefficient in a matrix</td><td>\code
168MatrixXf m;
169int row, col;
170
171// maximum value will be stored in maxValue
172// and the row and column where it was found in row and col,
173// (these two parameters are optional)
174float maxValue = m.maxCoeff(&row,&col);\endcode</td></tr>
175<tr><td>
176Product between all coefficients in a matrix</td><td>\code
177MatrixXf m;
178
179float product = m.prod();\endcode</td></tr>
180<tr><td>
181Mean of coefficients in a matrix</td><td>\code
182MatrixXf m;
183
184float mean = m.mean();\endcode</td></tr>
185<tr><td>
186Matrix's trace</td><td>\code
187MatrixXf m;
188
189float trace = m.trace();\endcode</td></tr>
190</table>
191
Benoit Jacobe078bb22010-06-26 14:00:00 -0400192\subsection TutorialArithmeticValidity Validity of operations
193Eigen checks the validity of the operations that you perform. When possible,
194it checks them at compile-time, producing compilation errors. These error messages can be long and ugly,
195but Eigen writes the important message in UPPERCASE_LETTERS_SO_IT_STANDS_OUT. For example:
196\code
197 Matrix3f m;
198 Vector4f v;
199 v = m*v; // Compile-time error: YOU_MIXED_MATRICES_OF_DIFFERENT_SIZES
200\endcode
Carlos Becker9d440052010-06-25 20:16:12 -0400201
Benoit Jacobe078bb22010-06-26 14:00:00 -0400202Of course, in many cases, for example when checking dynamic sizes, the check cannot be performed at compile time.
203Eigen then uses runtime assertions. This means that executing an illegal operation will result in a crash at runtime,
204with an error message.
Carlos Becker9d440052010-06-25 20:16:12 -0400205
Benoit Jacobe078bb22010-06-26 14:00:00 -0400206\code
207 MatrixXf m(3,3);
208 VectorXf v(4);
209 v = m * v; // Run-time assertion failure here: "invalid matrix product"
210\endcode
211
212For more details on this topic, see \ref TopicAssertions "this page".
213
214\li \b Next: \ref TutorialArrayClass
Carlos Becker9d440052010-06-25 20:16:12 -0400215
216*/
217
218}