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?
I assume that you have numeric values. A much more efficient way would be
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:
Your pattern will match an object with an explicit negative sign:
You could combine the patterns to match either:
Since this has become a speed competition (which is fine by me), rather than the beginner's question I took it to be, here is my own variation, using
For numeric values, the following:
is 50% faster than Thomas' solution.
Update: An even faster approach will be to compile to C, as shown in the following function
Using the timeAvg function, as defined in Mr. Wizard's answer, we have:
Note that the function
For the dangers with the use of
This seems competitive in terms of speed:
Lots of nice answers. Here's another, but I'm afraid it's quite slow.
Though this totals all the negative numbers. To count them you could do:
Then I got to thinking, "how would I program this in Matlab?"
I've found the fastest way to do this sort of thing is to use a very simple procedural