In my code (Python+numpy or Matlab, but issue can apply to any array programming language), I often need to count the number of elements in an array where the elements are true. Usually, I implement this as sum(x>0.5)
, but this may be considered improper. See Is it correct to add booleans in order to count the number of true values in a vector?. Numpy has count_nonzero
, but if there is no special-purpose function, what would be the proper way to write this?
For example, in Matlab
, I can either write sum(x>.5)
or length(find(x>0.5))
. The former is slightly faster but may be considered improper (see above). Are there any other alternatives for counting the number of true values in an array, and what should be my criteria for selecting one?
(In a low-level language, one would write an explicit for-loop, but that is an extremely inefficient way to implement this in a high-level array programming language)
length(find(x>0.5))
is definitely more clear thansum(x>.5)
. If there is another one even more clear, I would choose that one. One more good idea would be to throw in a small trivial function with an appropriate name, something likecount_true
. – Vlad Feb 18 '13 at 13:33sum(x>0.5)
as thesum of all the elements greater than 5
, rather thanthe count of all the elements greater than 5
. Clearly, a different intent, probably derived from the fact that I'm not a Python expert. – JohnL Feb 18 '13 at 13:47