Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a constant eigen matrix in a header file

Tags:

c++

eigen

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?

like image 385
Hailiang Zhang Avatar asked Sep 23 '14 15:09

Hailiang Zhang


People also ask

How do you initialize Eigen vectors?

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.

What is VectorXd?

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.


Video Answer


3 Answers

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);
like image 65
ggael Avatar answered Oct 20 '22 16:10

ggael


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;
}
like image 41
Neil Kirk Avatar answered Oct 20 '22 16:10

Neil Kirk


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

like image 43
0xfee1dead Avatar answered Oct 20 '22 16:10

0xfee1dead