28

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.

Mr. Llama
  • 20,202
  • 2
  • 62
  • 115
Matt Stokes
  • 4,618
  • 9
  • 33
  • 56

3 Answers3

44

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();
Frik
  • 1,054
  • 1
  • 13
  • 16
  • 4
    This is a great answer, upvoted! It's definitely more elegant than mine, I didn't know you can do it this way. – vsoftco Mar 09 '17 at 17:14
17

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.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
6

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;
}();
Dawid
  • 623
  • 3
  • 9
  • seems very nice, although I'm getting `error: conversion from 'Eigen::CommaInitializer >' to non-scalar type 'Eigen::Matrix4d {aka Eigen::Matrix}' requested }();` – vsoftco Jul 21 '15 at 21:14
  • I get the `error: C2440: 'initializing' : cannot convert from 'Eigen::CommaInitializer' to 'Eigen::Matrix' with [Derived=Eigen::Matrix] Constructor for class 'Eigen::Matrix' is declared 'explicit'` – Matt Stokes Jul 21 '15 at 21:15
  • 1
    @MattStokes the small issue is that the result of `Matrix4d << a,b,c,...` is an object of type `CommaInitializer`, which is not convertible to `Matrix4d`. – vsoftco Jul 21 '15 at 21:20
  • Yes, sorry for that. Please look at fixed version. – Dawid Jul 21 '15 at 21:33