Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error mixing types with Eigen matrices

Tags:

c++

casting

eigen

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?

like image 975
Fantastic Mr Fox Avatar asked May 30 '14 03:05

Fantastic Mr Fox


1 Answers

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.

like image 146
Fantastic Mr Fox Avatar answered Nov 04 '22 23:11

Fantastic Mr Fox