I would like to count the negative values of a list.
My approach was Count[data, -_]
which doesn't work.
How can I tell Mathematica to count all numbers with a negative sign?
Answer
I assume that you have numeric values. A much more efficient way would be
-Total[UnitStep[data] - 1]]
or
Total[1-UnitStep[data]]
Note: While the second notation is certainly a bit more compact, it is about 35% slower than the double-minus notation. I have no idea why. On my system, it takes on average 0.22 sec vs 0.30 sec.
Compare timings between the faster UnitStep version and the pattern matching approach:
data = RandomReal[{-10, 10}, 10^7];
Timing[-Total[UnitStep[data] - 1]]
(* ==> {0.222, 5001715} *)
Timing[Count[data, _?Negative]]
(* ==> {6.734, 5001715} *)
Comments
Post a Comment