You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

229 lines
10 KiB

  1. namespace Eigen {
  2. /** \page TutorialMatrixArithmetic Tutorial page 2 - %Matrix and vector arithmetic
  3. \ingroup Tutorial
  4. \li \b Previous: \ref TutorialMatrixClass
  5. \li \b Next: \ref TutorialArrayClass
  6. This tutorial aims to provide an overview and some details on how to perform arithmetic
  7. between matrices, vectors and scalars with Eigen.
  8. \b Table \b of \b contents
  9. - \ref TutorialArithmeticIntroduction
  10. - \ref TutorialArithmeticAddSub
  11. - \ref TutorialArithmeticScalarMulDiv
  12. - \ref TutorialArithmeticMentionXprTemplates
  13. - \ref TutorialArithmeticTranspose
  14. - \ref TutorialArithmeticMatrixMul
  15. - \ref TutorialArithmeticDotAndCross
  16. - \ref TutorialArithmeticRedux
  17. - \ref TutorialArithmeticValidity
  18. \section TutorialArithmeticIntroduction Introduction
  19. Eigen offers matrix/vector arithmetic operations either through overloads of common C++ arithmetic operators such as +, -, *,
  20. or through special methods such as dot(), cross(), etc.
  21. For the Matrix class (matrices and vectors), operators are only overloaded to support
  22. linear-algebraic operations. For example, \c matrix1 \c * \c matrix2 means matrix-matrix product,
  23. and \c vector \c + \c scalar is just not allowed. If you want to perform all kinds of array operations,
  24. not linear algebra, see the \ref TutorialArrayClass "next page".
  25. \section TutorialArithmeticAddSub Addition and subtraction
  26. The left hand side and right hand side must, of course, have the same numbers of rows and of columns. They must
  27. also have the same \c Scalar type, as Eigen doesn't do automatic type promotion. The operators at hand here are:
  28. \li binary operator + as in \c a+b
  29. \li binary operator - as in \c a-b
  30. \li unary operator - as in \c -a
  31. \li compound operator += as in \c a+=b
  32. \li compound operator -= as in \c a-=b
  33. <table class="example">
  34. <tr><th>Example:</th><th>Output:</th></tr>
  35. <tr><td>
  36. \include tut_arithmetic_add_sub.cpp
  37. </td>
  38. <td>
  39. \verbinclude tut_arithmetic_add_sub.out
  40. </td></tr></table>
  41. \section TutorialArithmeticScalarMulDiv Scalar multiplication and division
  42. Multiplication and division by a scalar is very simple too. The operators at hand here are:
  43. \li binary operator * as in \c matrix*scalar
  44. \li binary operator * as in \c scalar*matrix
  45. \li binary operator / as in \c matrix/scalar
  46. \li compound operator *= as in \c matrix*=scalar
  47. \li compound operator /= as in \c matrix/=scalar
  48. <table class="example">
  49. <tr><th>Example:</th><th>Output:</th></tr>
  50. <tr><td>
  51. \include tut_arithmetic_scalar_mul_div.cpp
  52. </td>
  53. <td>
  54. \verbinclude tut_arithmetic_scalar_mul_div.out
  55. </td></tr></table>
  56. \section TutorialArithmeticMentionXprTemplates A note about expression templates
  57. This is an advanced topic that we explain on \ref TopicEigenExpressionTemplates "this page",
  58. but it is useful to just mention it now. In Eigen, arithmetic operators such as \c operator+ don't
  59. perform any computation by themselves, they just return an "expression object" describing the computation to be
  60. performed. The actual computation happens later, when the whole expression is evaluated, typically in \c operator=.
  61. While this might sound heavy, any modern optimizing compiler is able to optimize away that abstraction and
  62. the result is perfectly optimized code. For example, when you do:
  63. \code
  64. VectorXf a(50), b(50), c(50), d(50);
  65. ...
  66. a = 3*b + 4*c + 5*d;
  67. \endcode
  68. Eigen compiles it to just one for loop, so that the arrays are traversed only once. Simplifying (e.g. ignoring
  69. SIMD optimizations), this loop looks like this:
  70. \code
  71. for(int i = 0; i < 50; ++i)
  72. a[i] = 3*b[i] + 4*c[i] + 5*d[i];
  73. \endcode
  74. Thus, you should not be afraid of using relatively large arithmetic expressions with Eigen: it only gives Eigen
  75. more opportunities for optimization.
  76. \section TutorialArithmeticTranspose Transposition and conjugation
  77. The transpose \f$ a^T \f$, conjugate \f$ \bar{a} \f$, and adjoint (i.e., conjugate transpose) \f$ a^* \f$ of a matrix or vector \f$ a \f$ are obtained by the member functions \link DenseBase::transpose() transpose()\endlink, \link MatrixBase::conjugate() conjugate()\endlink, and \link MatrixBase::adjoint() adjoint()\endlink, respectively.
  78. <table class="example">
  79. <tr><th>Example:</th><th>Output:</th></tr>
  80. <tr><td>
  81. \include tut_arithmetic_transpose_conjugate.cpp
  82. </td>
  83. <td>
  84. \verbinclude tut_arithmetic_transpose_conjugate.out
  85. </td></tr></table>
  86. For real matrices, \c conjugate() is a no-operation, and so \c adjoint() is equivalent to \c transpose().
  87. As for basic arithmetic operators, \c transpose() and \c adjoint() simply return a proxy object without doing the actual transposition. If you do <tt>b = a.transpose()</tt>, then the transpose is evaluated at the same time as the result is written into \c b. However, there is a complication here. If you do <tt>a = a.transpose()</tt>, then Eigen starts writing the result into \c a before the evaluation of the transpose is finished. Therefore, the instruction <tt>a = a.transpose()</tt> does not replace \c a with its transpose, as one would expect:
  88. <table class="example">
  89. <tr><th>Example:</th><th>Output:</th></tr>
  90. <tr><td>
  91. \include tut_arithmetic_transpose_aliasing.cpp
  92. </td>
  93. <td>
  94. \verbinclude tut_arithmetic_transpose_aliasing.out
  95. </td></tr></table>
  96. This is the so-called \ref TopicAliasing "aliasing issue". In "debug mode", i.e., when \ref TopicAssertions "assertions" have not been disabled, such common pitfalls are automatically detected.
  97. For \em in-place transposition, as for instance in <tt>a = a.transpose()</tt>, simply use the \link DenseBase::transposeInPlace() transposeInPlace()\endlink function:
  98. <table class="example">
  99. <tr><th>Example:</th><th>Output:</th></tr>
  100. <tr><td>
  101. \include tut_arithmetic_transpose_inplace.cpp
  102. </td>
  103. <td>
  104. \verbinclude tut_arithmetic_transpose_inplace.out
  105. </td></tr></table>
  106. There is also the \link MatrixBase::adjointInPlace() adjointInPlace()\endlink function for complex matrices.
  107. \section TutorialArithmeticMatrixMul Matrix-matrix and matrix-vector multiplication
  108. Matrix-matrix multiplication is again done with \c operator*. Since vectors are a special
  109. case of matrices, they are implicitly handled there too, so matrix-vector product is really just a special
  110. case of matrix-matrix product, and so is vector-vector outer product. Thus, all these cases are handled by just
  111. two operators:
  112. \li binary operator * as in \c a*b
  113. \li compound operator *= as in \c a*=b (this multiplies on the right: \c a*=b is equivalent to <tt>a = a*b</tt>)
  114. <table class="example">
  115. <tr><th>Example:</th><th>Output:</th></tr>
  116. <tr><td>
  117. \include tut_arithmetic_matrix_mul.cpp
  118. </td>
  119. <td>
  120. \verbinclude tut_arithmetic_matrix_mul.out
  121. </td></tr></table>
  122. Note: if you read the above paragraph on expression templates and are worried that doing \c m=m*m might cause
  123. aliasing issues, be reassured for now: Eigen treats matrix multiplication as a special case and takes care of
  124. introducing a temporary here, so it will compile \c m=m*m as:
  125. \code
  126. tmp = m*m;
  127. m = tmp;
  128. \endcode
  129. If you know your matrix product can be safely evaluated into the destination matrix without aliasing issue, then you can use the \link MatrixBase::noalias() noalias()\endlink function to avoid the temporary, e.g.:
  130. \code
  131. c.noalias() += a * b;
  132. \endcode
  133. For more details on this topic, see the page on \ref TopicAliasing "aliasing".
  134. \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.
  135. \section TutorialArithmeticDotAndCross Dot product and cross product
  136. For dot product and cross product, you need the \link MatrixBase::dot() dot()\endlink and \link MatrixBase::cross() cross()\endlink methods. Of course, the dot product can also be obtained as a 1x1 matrix as u.adjoint()*v.
  137. <table class="example">
  138. <tr><th>Example:</th><th>Output:</th></tr>
  139. <tr><td>
  140. \include tut_arithmetic_dot_cross.cpp
  141. </td>
  142. <td>
  143. \verbinclude tut_arithmetic_dot_cross.out
  144. </td></tr></table>
  145. Remember that cross product is only for vectors of size 3. Dot product is for vectors of any sizes.
  146. When using complex numbers, Eigen's dot product is conjugate-linear in the first variable and linear in the
  147. second variable.
  148. \section TutorialArithmeticRedux Basic arithmetic reduction operations
  149. Eigen also provides some reduction operations to reduce a given matrix or vector to a single value such as the sum (computed by \link DenseBase::sum() sum()\endlink), product (\link DenseBase::prod() prod()\endlink), or the maximum (\link DenseBase::maxCoeff() maxCoeff()\endlink) and minimum (\link DenseBase::minCoeff() minCoeff()\endlink) of all its coefficients.
  150. <table class="example">
  151. <tr><th>Example:</th><th>Output:</th></tr>
  152. <tr><td>
  153. \include tut_arithmetic_redux_basic.cpp
  154. </td>
  155. <td>
  156. \verbinclude tut_arithmetic_redux_basic.out
  157. </td></tr></table>
  158. The \em trace of a matrix, as returned by the function \link MatrixBase::trace() trace()\endlink, is the sum of the diagonal coefficients and can also be computed as efficiently using <tt>a.diagonal().sum()</tt>, as we will see later on.
  159. There also exist variants of the \c minCoeff and \c maxCoeff functions returning the coordinates of the respective coefficient via the arguments:
  160. <table class="example">
  161. <tr><th>Example:</th><th>Output:</th></tr>
  162. <tr><td>
  163. \include tut_arithmetic_redux_minmax.cpp
  164. </td>
  165. <td>
  166. \verbinclude tut_arithmetic_redux_minmax.out
  167. </td></tr></table>
  168. \section TutorialArithmeticValidity Validity of operations
  169. Eigen checks the validity of the operations that you perform. When possible,
  170. it checks them at compile time, producing compilation errors. These error messages can be long and ugly,
  171. but Eigen writes the important message in UPPERCASE_LETTERS_SO_IT_STANDS_OUT. For example:
  172. \code
  173. Matrix3f m;
  174. Vector4f v;
  175. v = m*v; // Compile-time error: YOU_MIXED_MATRICES_OF_DIFFERENT_SIZES
  176. \endcode
  177. Of course, in many cases, for example when checking dynamic sizes, the check cannot be performed at compile time.
  178. Eigen then uses runtime assertions. This means that the program will abort with an error message when executing an illegal operation if it is run in "debug mode", and it will probably crash if assertions are turned off.
  179. \code
  180. MatrixXf m(3,3);
  181. VectorXf v(4);
  182. v = m * v; // Run-time assertion failure here: "invalid matrix product"
  183. \endcode
  184. For more details on this topic, see \ref TopicAssertions "this page".
  185. \li \b Next: \ref TutorialArrayClass
  186. */
  187. }