Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast dynamic matrix to fixed matrix in Eigen

Tags:

c++

eigen

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.

like image 733
marcman Avatar asked Jun 06 '17 17:06

marcman


1 Answers

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.

like image 170
ggael Avatar answered Nov 10 '22 20:11

ggael