Checking that all entries in the matrix are zero in the Eigen Library

First of all, I'm not sure if this is possible. I would like to check if the matrix is ​​equal to zero or not in the Eigen Library (note: I have to declare it). My solution is to check if all elements are equal to zero. My question is: is there another way to accomplish this task without resizing the matrix?

#include <iostream>
#include <Eigen/Dense>

// true if it is empty, false if not
bool isEmpty(Eigen::MatrixXd& Z)
{
   bool check = true;

   for (int row(0); row < Z.rows(); ++row)
    for (int col(0); col < Z.cols(); ++col){
        if ( Z(row,col) != 0 ){
            check = false;
            break;
        }
     }

   return check;
}


int main()
{
    Eigen::MatrixXd Z(3,3);

    if ( isEmpty(Z) )
        std::cout << Z.size() << std::endl;
    else
        Z.setZero(0,0); // resize the matrix (not clever way I know)

    std::cin.get();
    return 0;
}
+4
source share
1 answer

You can set all coefficients to zeros without changing the size of the matrix with:

Z.setZero();

You can check that all coefficients are zero:

bool is_empty = Z.isZero(0);

Here the argument is relative precision to verify that the number is a numeric zero. See this document .

+10
source

All Articles