Counting non-zeros in boolean matrices

Alec Jacobson

February 02, 2015

weblog/

Sometimes I'll use Eigen types with bool as the Scalar type. This invites "gotchas" when I assume the matrices will work like logicals do in MATLAB. Most immediately sum of logicals in matlab will return the integer number of trues (actually returns it as a double type). In Eigen, sum (not surprisingly) just calls operator+ and casts the result to bool again.

So rather than:

Matrix<bool,4,4> B;
B<<true,false,true,true;
B.sum(); // will just return true

if you want to compute the number of true entries use one of:

<del>B.nonZeros();</del>
B.count();
std::count(B.data(),B.data()+B.size(),true);

Things get trickier if your trying to use more advanced accessors. Consider trying to find the number of true entries per row. Instead of

B.rowwise().sum();

you could use

B.cast<int>().rowwise().sum();

but this casts the entire matrix first to int

B.rowwise().count();

or just roll up the loop over the rows.