Cast dynamic matrix to fixed matrix in Eigen

爱⌒轻易说出口 提交于 2020-01-01 11:10:06

问题


For flexibility, I'm loading data into dynamic-sized matrices (e.g. Eigen::MatrixXf) using the C++ library Eigen. I've written some functions which require mixed- or fixed-sized matrices as parameters (e.g. Eigen::Matrix<float, 3, Eigen::Dynamic> or Eigen::Matrix4f). Assuming I do the proper assertions for row and column size, how can I convert the dynamic matrix (size set at runtime) to a fixed matrix (size set at compile time)?

The only solution I can think of is to map it, for example:

Eigen::MatrixXf dyn = Eigen::MatrixXf::Random(3, 100);
Eigen::Matrix<float, 3, Eigen::Dynamic> fixed = 
    Eigen::Map<float, 3, Eigen::Dynamic>(dyn.data(), 3, dyn.cols());

But it's unclear to me if that will work either because the fixed size map constructor doesn't accept rows and columns as parameters in the docs. Is there a better solution? Simply assigning dynamic- to fixed-sized matrices doesn't work.


回答1:


You can use Ref for that purpose, it's usage in your case is simpler, and it will do the runtime assertion checks for you, e.g.:

MatrixXf A_dyn(4,4);
Ref<Matrix4f> A_fixed(A_dyn);

You might even require a fixed outer-stride and aligned memory:

 Ref<Matrix4f,Aligned16,OuterStride<4> > A_fixed(A_dyn);

In this case, A_fixed is really like a Matrix4f.



来源:https://stackoverflow.com/questions/44396703/cast-dynamic-matrix-to-fixed-matrix-in-eigen

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