This forum has been archived. All content is frozen. Please use KDE Discuss instead.

Sum of boolean Array is always 1?

Tags: None
(comma "," separated)
matriza
Registered Member
Posts
17
Karma
0

Sum of boolean Array is always 1?

Tue Jan 29, 2013 11:51 pm
Hi,

For some reason the sum of a boolean array is always 1, regardless of the entries, any idea why? How do I get the number of 1s in it?

Thanks.

Code: Select all
#include <iostream>
#include <Eigen/Core>
using namespace Eigen;

int main(void)
{
   MatrixXd X(3, 3);

   X << 1, 2, 3, 4, 5, 6, 7, 8, 9;

   std::cout << X << std::endl;

   Array<bool, Dynamic, Dynamic> Y = X.array() > 5;

   std::cout << Y << std::endl;

   std::cout << Y.sum() << std::endl;

   return 0;
}

$ /usr/local/bin/g++-4.7 -IEigen t.cpp -o t && ./t
1 2 3
4 5 6
7 8 9
0 0 0
0 0 1
1 1 1
1
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS
A boolean is either 0 or 1, so the result of any operation on boolean must be either 0 or 1. For your use case, you can either lazily cast to int:

Y.cast<int>().sum();

or use:

Y.count();
matriza
Registered Member
Posts
17
Karma
0
thanks!


Bookmarks



Who is online

Registered users: Bing [Bot], Google [Bot], Sogou [Bot], Yahoo [Bot]