Check if any element of Eigen::Matrix is different from zero

Nick picture Nick · Dec 2, 2015 · Viewed 7.6k times · Source

I have an Eigen::Matrix<double, Dynamic, Dynamic>, and I need to check if any of its elements is different from 0.

I tried the following code:

Matrix<double, Dynamic, Dynamic> m;
bool f = (m != 0.0).any();

But I got a compiler error.

Invalid operands to binary expression ('const Eigen::Matrix' and 'double')

Answer

Avi Ginsburg picture Avi Ginsburg · Dec 2, 2015

In Eigen, most of the element-wise operations are handled by an Array class. Fortunately, there is a simple way to use them on Matrix objects. Try

bool f = (m.array() != 0.0).any();