7

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')

Nick
  • 10,309
  • 21
  • 97
  • 201

2 Answers2

11

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();
Avi Ginsburg
  • 10,323
  • 3
  • 29
  • 56
2

Another option is

bool f = !m.isZero();

It should work for both Array and Matrix

ThomasHH
  • 21
  • 3