#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
using namespace std;
int main()
{
MatrixXd m = MatrixXd::Random(3, 3);
m = (m + MatrixXd::Constant(3, 3, 1.2)) * 50;
cout << "m =" << endl << m << endl;
VectorXd v(3);
v << 1, 2, 3;
cout << "m * v =" << endl << m * v << endl;
}
#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
using namespace std;
int main()
{
Matrix3d m = Matrix3d::Random();
m = (m + Matrix3d::Constant(1.2)) * 50;
cout << "m =" << endl << m << endl;
Vector3d v(1, 2, 3);
cout << "m * v =" << endl << m * v << endl;
}
The second example starts by declaring a 3-by-3 matrix m
which is initialized using the Random() method with random values between -1 and 1. The next line applies a linear mapping such that the values are between 10 and 110. The function call MatrixXd::Constant(3,3,1.2) returns a 3-by-3 matrix expression having all coefficients equal to 1.2. The rest is standard arithmetics.
The next line of the main
function introduces a new type: VectorXd
. This represents a (column) vector of arbitrary size. Here, the vector v
is created to contain 3
coefficients which are left unitialized. The one but last line uses the so-called comma-initializer, explained in Advanced initialization, to set all coefficients of the vector v
to be as follows:
The final line of the program multiplies the matrix m
with the vector v
and outputs the result.
Now look back at the second example program. We presented two versions of it. In the version in the left column, the matrix is of type MatrixXd
which represents matrices of arbitrary size. The version in the right column is similar, except that the matrix is of type Matrix3d
, which represents matrices of a fixed size (here 3-by-3). Because the type already encodes the size of the matrix, it is not necessary to specify the size in the constructor; compare MatrixXd m(3,3)
with Matrix3d m
. Similarly, we have VectorXd
on the left (arbitrary size) versus Vector3d
on the right (fixed size). Note that here the coefficients of vector v
are directly set in the constructor, though the same syntax of the left example could be used too.
The use of fixed-size matrices and vectors has two advantages. The compiler emits better (faster) code because it knows the size of the matrices and vectors. Specifying the size in the type also allows for more rigorous checking at compile-time. For instance, the compiler will complain if you try to multiply a Matrix4d
(a 4-by-4 matrix) with a Vector3d
(a vector of size 3). However, the use of many types increases compilation time and the size of the executable. The size of the matrix may also not be known at compile-time. A rule of thumb is to use fixed-size matrices for size 4-by-4 and smaller.