As shown above, static methods as Zero() and Constant() can be used to initialize variables at the time of declaration or at the right-hand side of an assignment operator. You can think of these methods as returning a matrix or array; in fact, they return so-called expression objects which evaluate to a matrix or array when needed, so that this syntax does not incur any overhead.
These expressions can also be used as a temporary object. The second example in the Getting started guide, which we reproduce here, already illustrates this.
Example: | Output: |
---|---|
#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;
}
| m = 94 89.8 43.5 49.4 101 86.8 88.3 29.8 37.8 m * v = 404 512 261 |
The expression m + MatrixXf::Constant(3,3,1.2)
constructs the 3-by-3 matrix expression with all its coefficients equal to 1.2 plus the corresponding coefficient of m.
The comma-initializer, too, can also be used to construct temporary objects. The following example constructs a random matrix of size 2-by-3, and then multiplies this matrix on the left with .
Example: | Output: |
---|---|
MatrixXf mat =
MatrixXf::Random(2, 3);
std::cout << mat << std::endl << std::endl;
mat = (
MatrixXf(2,2) << 0, 1, 1, 0).finished() * mat;
std::cout << mat << std::endl;
| 0.68 0.566 0.823 -0.211 0.597 -0.605 -0.211 0.597 -0.605 0.68 0.566 0.823 |
The finished() method is necessary here to get the actual matrix object once the comma initialization of our temporary submatrix is done.