Error mixing types with Eigen matrices
Asked Answered
S

1

31

There was no quick find answer that I could see on stack for this problem so I thought I would add one.

Say I have the following example code from the c++ Eigen Library:

Eigen::Matrix4d m1;
Eigen::Matrix4f m2;
m1 << 1, 2, 3, 4 ... 16
m2 = m1; //Compile error here.

I get a compile error on the final line that boils down to this:

YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY

What is an easy way to fix this?

Swirl answered 30/5, 2014 at 3:41 Comment(0)
S
47

So the way to fix this which took me an annoyingly long time to find is to use the derived cast method described here. Now the definition is this:

internal::cast_return_type<Derived,const CwiseUnaryOp<internal::scalar_cast_op<typenameinternal::traits<Derived>::Scalar, NewType>, const Derived> >::type cast() const

Which Ill admit, phased me a little. But turns out it is pretty easy (and the only explanation I could find was in the Eigen 2.0 doc which was frustrating). All you need to do is this:

m2 = m1.cast<float>();

Problem solved.

Swirl answered 30/5, 2014 at 3:41 Comment(2)
Any suggestion on how the documentation could be improved to make this easier to find?Fencer
@JitseNiesen Well the Eigen 2.0 had really good documentation for this: eigen.tuxfamily.org/dox-2.0/TutorialCore.html But it is difficult to find now that Eigen3 is the standard.Swirl

© 2022 - 2024 — McMap. All rights reserved.