Initialize a constant eigen matrix in a header file
Asked Answered
G

3

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?

Gluck answered 23/9, 2014 at 15:47 Comment(1)
If it's in a header file, the data may be copied for every source file that includes it, wasting memory.Stannfield
B
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);
Buttonhole answered 23/9, 2014 at 20:26 Comment(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?Woodenware
S
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;
}
Stannfield answered 23/9, 2014 at 15:58 Comment(0)
D
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...

Disagreement answered 23/9, 2014 at 16:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.