Cast dynamic matrix to fixed matrix in Eigen
Asked Answered
P

1

7

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.

Pericranium answered 6/6, 2017 at 17:54 Comment(4)
using dynamic size for flexibility and then casting to fixed size to call a function sounds like a contradiction. Do you really need the input to be dynamic size? I mean anyhow your function seems to expect a certain size...Barbershop
@tobi303: The reason is that I'm using the same loader function for different collections of data. Then, depending on what the data is that I've loaded, I call the processing function which requires the mixed or fixed size as parameters (due to typedefs)Pericranium
Yes, this should work. Not that in recent versions (at least from 3.2.9), you should be able to do it without using Eigen::Map.Hookworm
Not sure what you tried, but Eigen::Matrix<float, 3, Eigen::Dynamic> fixed = dyn; should work without problems. If not, please add the error you get when writing this. This conversoin does result in copying all coefficients, however (which may not be what you want).Ventre
T
5

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.

Transcaucasia answered 7/6, 2017 at 7:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.