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
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)