Cast dynamic matrix to fixed matrix in Eigen

2019-04-08 23:42发布

问题:

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.



标签: c++ eigen