Search code examples
c++eigen

Initialize a constant eigen matrix in a header file


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?


Solution

  • 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);