Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

eigen3

First of all, I'm not really sure if this is possible. I would like to check whether a matrix is zero or not in Eigen Library (note: I have to declare it). My solution is to check if all elements are zero. My question is Is there another way fulfill this task while keeping the size of the matrix unchanged?

#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;
}
like image 323
CroCo Avatar asked Jul 31 '14 09:07

CroCo


1 Answers

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

Z.setZero();

You can check that all coefficients are zero with:

bool is_empty = Z.isZero(0);

Here the argument is the relative precision to check that a number is a numerical zero. See this doc.

like image 77
ggael Avatar answered Oct 19 '22 18:10

ggael