C++ Eigen initialize static matrix

时光毁灭记忆、已成空白 提交于 2020-01-12 04:27:32

问题


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.


回答1:


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.




回答2:


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();



回答3:


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;
}();


来源:https://stackoverflow.com/questions/31549398/c-eigen-initialize-static-matrix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!