This is a question that can be answered by non-Eigen user...
I want to use the Eigen API to initialize a constant matrix in a header file, but Eigen seems not providing a constructor to achieve this, and following is what I tried:
// tried the following first, but Eigen does not provide such a constructor
//const Eigen::Matrix3f M<<1,2,3,4,5,6,7,8,9;
// then I tried the following, but this is not allowed in header file
//const Eigen::Matrix3f M;
//M <<1,2,3,4,5,6,7,8,9; // not allowed in header file
What is the alternative to achieve this in a header file?
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.
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 uninitialized.
There are at least two possibilities. The first one is using the comma initialiser features of Eigen:
Eigen::Matrix3d A((Eigen::Matrix3d() << 1, 2, 3, 4, 5, 6, 7, 8, 9).finished());
The second is using the Matrix3d(const double*)
constructor which copies data from a raw pointer. In this case, the values must be provided in the same order than the storage order of the destination, so column-wise in most cases:
const double B_data[] = {1, 4, 7, 2, 5, 8, 3, 6, 9};
Eigen::Matrix3d B(B_data);
You can't put arbitrary code outside of a function like that.
Try the following. The implementation can even be in a source file for faster compiling.
const Eigen::Matrix3f& GetMyConst()
{
static const struct Once
{
Eigen::Matrix3f M;
Once()
{
M <<1,2,3,4,5,6,7,8,9;
}
} once;
return once.M;
}
I have not seen a way to do it completely in a Header but this should work:
const Eigen::Matrix3f& getMyConst()
{
static Eigen::Matrix3f _myConstMatrix((Eigen::Matrix3f() << 1,2,3,4,5,6,7,8,9).finished()));
return _myConstMatrix;
}
#define myConst getMyConst() // To access it like a variable without "()"
I have never worked with Eigen so I cant test it...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With