Eigen offers a comma initializer syntax which allows the user to easily set all the coefficients of a matrix, vector or array. Simply list the coefficients, starting at the top-left corner and moving from left to right and from the top to the bottom. The size of the object needs to be specified beforehand. If you list too few or too many coefficients,Eigen will complain.
Example: | Output: |
---|---|
1 2 3 4 5 6 7 8 9 |
Moreover, the elements of the initialization list may themselves be vectors or matrices. A common use is to join vectors or matrices together. For example, here is how to join two row vectors together. Remember that you have to set the size before you can use the comma initializer.
Example: | Output: |
---|---|
RowVectorXd vec1(3);
vec1 << 1, 2, 3;
std::cout <<
"vec1 = " << vec1 << std::endl;
RowVectorXd vec2(4);
vec2 << 1, 4, 9, 16;;
std::cout <<
"vec2 = " << vec2 << std::endl;
RowVectorXd joined(7);
joined << vec1, vec2;
std::cout <<
"joined = " << joined << std::endl;
| vec1 = 1 2 3 vec2 = 1 4 9 16 joined = 1 2 3 1 4 9 16 |
We can use the same technique to initialize matrices with a block structure.
Example: | Output: |
---|---|
1 2 0.1 0.2 3 4 0.3 0.4 0.1 0.2 1 2 0.3 0.4 3 4 |
The comma initializer can also be used to fill block expressions such as m.row(i)
. Here is a more complicated way to get the same result as in the first example above:
Example: | Output: |
---|---|
Matrix3f m;
m.row(0) << 1, 2, 3;
m.block(1,0,2,2) << 4, 5, 7, 8;
m.col(2).tail(2) << 6, 9;
std::cout << m;
| 1 2 3 4 5 6 7 8 9 |