Matt Stokes
Matt Stokes

Reputation: 4968

C++ Eigen initialize static matrix

Is it possible to initialize a static eigen matrix4d in a header file? I want to use it as a global variable.

I'd like to do something along the lines of:

static Eigen::Matrix4d foo = Eigen::Matrix4d(1, 2 ... 16);

Or similar to vectors:

static Eigen::Matrix4d foo = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}; 

Here is a link to the eigen matrix docs. I can't seem to find how to do this from there.

Upvotes: 29

Views: 32618

Answers (3)

Frik
Frik

Reputation: 1094

A more elegant solution might include the use of finished(). The function returns 'the built matrix once all its coefficients have been set.'

E.g:

static Eigen::Matrix4d foo = (Eigen::Matrix4d() << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16).finished();

Upvotes: 47

Dawid
Dawid

Reputation: 643

You can use initialization lambda like this:

static Eigen::Matrix4d foo = [] { 
  Eigen::Matrix4d matrix;
  matrix << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16;
  return matrix;
}();

Upvotes: 7

vsoftco
vsoftco

Reputation: 56577

On the lines of Dawid's answer (which has a small issue, see the comments), you can do:

static Eigen::Matrix4d foo = [] {
    Eigen::Matrix4d tmp;
    tmp << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16;
    return tmp;
}();

Return value optimization takes care of the temporary, so no worries about an extra copy.

Upvotes: 18

Related Questions