How do I compute the absolute value of a vector in Eigen?

Reed Richards picture Reed Richards · Aug 16, 2014 · Viewed 12.5k times · Source

How do I compute the absolute value of a vector in Eigen? Since the obvious way

Eigen::VectorXf v(-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0);
v.abs(); // Compute abs value.

does not work.

Answer

Reed Richards picture Reed Richards · Aug 16, 2014

For Eigen 3.2.1 using p.abs(); in the same way as you would use p.normalize results in a compiler error along the lines of

error: no member named 'abs' in 'Eigen::Matrix' p.abs(); ~ ^

so a vector in Eigen is nothing but a Matrix type. To compute the absolute values of a matrix in Eigen one can use p.cwiseAbs() or array conversion p.array().abs();. Both these absolute functions returns a value rather than modifying the variable itself.

So a correct way of doing it would be to do

p = p.cwiseAbs();

or

p = p.array().abs();