8

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;
}
Sobi
  • 117
  • 6
CroCo
  • 5,531
  • 9
  • 56
  • 88
  • 2
    An empty matrix is a matrix with 0 cols or 0 rows, isn't it? – Kknd Aug 01 '14 at 11:37
  • 1
    Why the downvote? This is really getting weird with some mentalities. I have a problem and I've shown my effort and my way to solve it. What do really those ppl want? – CroCo Aug 01 '14 at 11:44
  • @Kknd, it depends on which language you use. – CroCo Aug 01 '14 at 11:48
  • is empty and is filled with Zeros are not the same. Probably explains the down votes. "is empty" usually means it is nullptr – Yonatan Simson Mar 29 '17 at 14:02

1 Answers1

17

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.

ggael
  • 28,425
  • 2
  • 65
  • 71