00049-Eigen 学习笔记-ubuntu
前言
Eigen is a C++ template library for linear algebra: matrices, vectors, numerical solvers, and related algorithms.
Eigen
的官网地址为:https://eigen.tuxfamily.org/index.php?title=Main_Page 。
操作系统:Ubuntu 20.04.5 LTS
参考文档
安装 Eigen
1 | sudo apt install libeigen3-dev |
官方
官方教程链接: https://eigen.tuxfamily.org/dox/group__TutorialMatrixArithmetic.html .
This page aims to provide an overview and some details on how to perform arithmetic between matrices
, vectors
and scalars
with Eigen.
Introduction
Eigen offers matrix/vector arithmetic operations either through overloads of common C++ arithmetic operators such as +
, -
, *
, or through special methods such as dot()
, cross()
, etc. For the Matrix class (matrices and vectors), operators are only overloaded to support linear-algebraic operations. For example, matrix1 * matrix2
means matrix-matrix product
, and vector + scalar
is just not allowed
. If you want to perform all kinds of array operations, not linear algebra, see the next page.
Addition and subtraction
The left hand side and right hand side must, of course, have the same numbers of rows and of columns. They must also have the same Scalar type, as Eigen doesn’t do automatic type promotion. The operators at hand here are:
-
binary operator + as in a+b
-
binary operator - as in a-b
-
unary operator - as in -a
-
compound operator += as in a+=b
-
compound operator -= as in a-=b
1 |
|
Output:
1 | a + b = |
Scalar multiplication and division
Multiplication and division by a scalar is very simple too. The operators at hand here are:
-
binary operator
*
as inmatrix*scalar
-
binary operator
*
as inscalar*matrix
-
binary operator
/
as inmatrix/scalar
-
compound operator
*=
as inmatrix*=scalar
-
compound operator
/=
as inmatrix/=scalar
1 |
|
Output:
1 | a * 2.5 = |
A note about expression templates
This is an advanced topic that we explain on this page, but it is useful to just mention it now. In Eigen, arithmetic operators such as operator+ don’t perform any computation by themselves, they just return an “expression object” describing the computation to be performed. The actual computation happens later, when the whole expression is evaluated, typically in operator=. While this might sound heavy, any modern optimizing compiler is able to optimize away that abstraction and the result is perfectly optimized code. For example, when you do:
1 | VectorXf a(50), b(50), c(50), d(50); |
Eigen compiles it to just one for loop, so that the arrays are traversed only once. Simplifying (e.g. ignoring SIMD optimizations), this loop looks like this:
1 | for(int i = 0; i < 50; ++i) |
Thus, you should not be afraid of using relatively large arithmetic expressions with Eigen: it only gives Eigen more opportunities for optimization.
Transposition and conjugation
The transpose , conjugate , and adjoint (i.e., conjugate transpose) of a matrix or vector a are obtained by the member functions transpose()
, conjugate()
, and adjoint()
, respectively.
1 | MatrixXcf a = MatrixXcf::Random(2,2); |
Output:
1 | Here is the matrix a |
For real matrices, conjugate() is a no-operation, and so adjoint() is equivalent to transpose().
As for basic arithmetic operators, transpose()
and adjoint()
simply return a proxy object without doing the actual transposition. If you do b = a.transpose()
, then the transpose is evaluated at the same time as the result is written into b
. However, there is a complication here. If you do a = a.transpose()
, then Eigen starts writing the result into a before the evaluation of the transpose is finished. Therefore, the instruction a = a.transpose() does not replace a with its transpose, as one would expect:
1 | Matrix2i a; a << 1, 2, 3, 4; |
Output:
1 | Here is the matrix a: |
This is the so-called aliasing issue. In “debug mode”, i.e., when assertions have not been disabled, such common pitfalls are automatically detected.
For in-place transposition, as for instance in a = a.transpose(), simply use the transposeInPlace() function:
1 | MatrixXf a(2,3); a << 1, 2, 3, 4, 5, 6; |
Output:
1 | Here is the initial matrix a: |
There is also the adjointInPlace()
function for complex matrices.
Matrix-matrix and matrix-vector multiplication
Matrix-matrix multiplication
is again done with operator*
. Since vectors are a special case of matrices, they are implicitly handled there too, so matrix-vector product is really just a special case of matrix-matrix product, and so is vector-vector outer product. Thus, all these cases are handled by just two operators:
-
binary operator
*
as ina*b
-
compound operator
*=
as ina*=b
(this multiplies on the right:a*=b
is equivalent toa = a*b
)
1 |
|
Output:
1 | Here is mat*mat: |
Note: if you read the above paragraph on expression templates and are worried that doing m=m*m
might cause aliasing issues, be reassured for now: Eigen treats matrix multiplication as a special case and takes care of introducing a temporary here, so it will compile m=m*m as
:
1 | tmp = m*m; |
If you know your matrix product can be safely evaluated into the destination matrix without aliasing issue, then you can use the noalias()
function to avoid the temporary, e.g.:
1 | c.noalias() += a * b; |
For more details on this topic, see the page on aliasing.
Note: for BLAS users worried about performance, expressions such as c.noalias() -= 2 * a.adjoint() * b;
are fully optimized and trigger a single gemm-like function call.
Dot product and cross product
For dot product and cross product, you need the dot()
and cross()
methods. Of course, the dot product can also be obtained as a 1x1 matrix as u.adjoint()*v
.
1 |
|
Output:
1 | Dot product: 8 |
Remember that cross product is only for vectors of size 3. Dot product is for vectors of any sizes. When using complex numbers, Eigen’s dot product is conjugate-linear in the first variable and linear in the second variable.
Basic arithmetic reduction operations
Eigen also provides some reduction operations to reduce a given matrix or vector to a single value such as the sum
(computed by sum()
), product
(prod()
), or the maximum
(maxCoeff()
) and minimum
(minCoeff()
) of all its coefficients.
1 |
|
Output:
1 | Here is mat.sum(): 10 |
The trace of a matrix, as returned by the function trace()
, is the sum of the diagonal coefficients and can also be computed as efficiently using a.diagonal().sum(), as we will see later on.
There also exist variants of the minCoeff
and maxCoeff
functions returning the coordinates of the respective coefficient via the arguments:
1 | Matrix3f m = Matrix3f::Random(); |
Output:
1 | Here is the matrix m: |
Validity of operations
Eigen checks the validity of the operations that you perform. When possible, it checks them at compile time, producing compilation errors. These error messages can be long and ugly, but Eigen writes the important message in UPPERCASE_LETTERS_SO_IT_STANDS_OUT. For example:
1 | Matrix3f m; |
Of course, in many cases, for example when checking dynamic sizes, the check cannot be performed at compile time. 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.
1 | MatrixXf m(3,3); |
For more details on this topic, see this page.
大佬总结
源教程链接: https://blog.csdn.net/ycrsw/article/details/123784649 .
定义头和命名空间:
1 |
|
向量
定义一个三维 float 向量:
1 | Vector3f v(1.0f,2.0f,3.0f); |
定义一个三维 int 向量:
1 | Vector3i v(1, 2, 3);//同样有两种,不再赘述 |
定义一个二维 int/double/float 向量:
1 | Vector2i v; |
定义一个 50(任意)维 float 向量:
1 | VectorXf a(50);//VectorXf是任意维浮点向量,同理VectorXd是任意维整数向量 |
定义一个随机四维 int 行向量:
1 | RowVector4i v = RowVector4i::Random(); |
向量相加、数乘:
1 | Vector3f v(1.0f,2.0f,3.0f); |
向量方法集合:
1 | v.dot(w)//v点乘w |
矩阵
定义一个 3*3 float 矩阵:
1 | Matrix3f i,j; |
定义一个 3*3 double 矩阵:
1 | Matrix3d i; |
定义一个 3*3 随机 float 矩阵:
1 | Matrix3f m = Matrix3f::Random(); |
定义一个2*2(任意)虚数 float 矩阵:
1 | MatrixXcf a = MatrixXcf::Random(2,2); |
定义一个 2*3(任意)float 矩阵:
1 | MatrixXf a(2,3); |
矩阵相乘、矩阵向量相乘:
1 | Matrix2d mat; |
矩阵方法集合:
1 | mat.sum()//矩阵元素和 |
注意: 转置方法是元素依次处理的, 所以如果你要对矩阵自身转置, 不要用
a = a.transpose();
而是用a.transposeInPlace();
结语
第四十九篇博文写完,开心!!!!
今天,也是充满希望的一天。