Error mixing types with Eigen matrices

Fantastic Mr Fox picture Fantastic Mr Fox · May 30, 2014 · Viewed 13.9k times · Source

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?

Answer

Fantastic Mr Fox picture Fantastic Mr Fox · May 30, 2014

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.