C++ Eigen initialize static matrix
Asked Answered
Y

3

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.

Yardstick answered 21/7, 2015 at 20:52 Comment(0)
D
45

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();
Dromous answered 3/2, 2016 at 7:3 Comment(1)
This is a great answer, upvoted! It's definitely more elegant than mine, I didn't know you can do it this way.Funches
F
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.

Funches answered 21/7, 2015 at 21:18 Comment(0)
M
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;
}();
Mansur answered 21/7, 2015 at 21:8 Comment(4)
seems very nice, although I'm getting error: conversion from 'Eigen::CommaInitializer<Eigen::Matrix<double, 4, 4> >' to non-scalar type 'Eigen::Matrix4d {aka Eigen::Matrix<double, 4, 4>}' requested }();Funches
I get the error: C2440: 'initializing' : cannot convert from 'Eigen::CommaInitializer<Derived>' to 'Eigen::Matrix<double,4,4,0,4,4>' with [Derived=Eigen::Matrix<double,4,4,0,4,4>] Constructor for class 'Eigen::Matrix<double,4,4,0,4,4>' is declared 'explicit'Yardstick
@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.Funches
Yes, sorry for that. Please look at fixed version.Mansur

© 2022 - 2024 — McMap. All rights reserved.