Search code examples
c++eigenabsolute-value

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


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.


Solution

  • 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();