11

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?

Hailiang Zhang
  • 17,604
  • 23
  • 71
  • 117
  • If it's in a header file, the data may be copied for every source file that includes it, wasting memory. – Neil Kirk Sep 24 '14 at 09:41

3 Answers3

14

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);
ggael
  • 28,425
  • 2
  • 65
  • 71
  • 1
    Doesn't the comma initializer fill a matrix row-wise whereas raw data array initialization assumes column-wise filling? So you'd get the transpose of the desired matrix? – Flo Ryan Dec 13 '17 at 08:15
1

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;
}
Neil Kirk
  • 21,327
  • 9
  • 53
  • 91
1

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...

0xfee1dead
  • 116
  • 1
  • 8