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

2

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

Demonolater answered 2/12, 2015 at 15:28 Comment(1)
not related to the error, but you should compare floating points to zero via (abs(m) < eps)Anguish
J
12

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();
Jennijennica answered 2/12, 2015 at 16:19 Comment(2)
Does the array() method create a new object? I am concerned about performance.Demonolater
Nope. It just treats the existing object as an Array.Jennijennica
C
2

Another option is

bool f = !m.isZero();

It should work for both Array and Matrix

Cauca answered 4/6, 2021 at 6:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.