I want to count the number of numbers lying between 0 and -1 in a vector called spec
.
I have tried Count[spec,spec<0 && spec>-1]
, but this does not work. There must be an easy answer...
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityI want to count the number of numbers lying between 0 and -1 in a vector called spec
.
I have tried Count[spec,spec<0 && spec>-1]
, but this does not work. There must be an easy answer...
SeedRandom[1]
spec = RandomReal[{-2, 2}, 100];
Tr[(1 - UnitStep[spec]) UnitStep[spec -(-1)]]
Tr@Unitize@Clip[spec, {-1, 0}, {0, 0}]
Count[spec, _?(-1 <= # <= 0 &)]
all give
24
Some timings:
SeedRandom[1]
s = RandomReal[{-2, 2}, 10^6];
Grid[{#, ClearSystemCache[]; AbsoluteTiming[#[s]]} & /@ {
Length@ Pick[#, Sign@Clip[#, {-1, 0}, {1, 1}], -1] &,
Tr[(1 - UnitStep[#]) UnitStep[# - (-1)]] &,
Tr@Unitize@Clip[#, {-1, 0}, {0, 0}] &,
Count[#, _?(-1 <= # <= 0 &)] &,
Total[Boole[-1 <= # <= 0] & /@ #] &,
Length@Select[#, And[# > -1, # < 0] &] &,
Length@Cases[#, x_ /; -1 < x < 0] &} ]
For SeedRandom[1];s = RandomReal[{-2, 2}, 10^7];
we get:
Note: Still on version 9, so cannot include CountsBy
in the timings table.
Total[Boole[-1 <= # <= 0] & /@ spec]
Unitize
and didn't think. Thanks :)
$\endgroup$
SeedRandom[1]
spec = RandomReal[{-2, 2}, 100];
CountsBy[spec, -1 <= # <= 0 &]
CountsBy[spec, -1 <= # <= 0 &][True]
24
Update
This one is very fast:
s = RandomReal[{-2, 2}, 10^6];
Length @ Pick[s, Sign @ Clip[s, {-1, 0}, {1, 1}], -1] // AbsoluteTiming
{0.032002, 249536}
Select[spec, And[# > -1, # < 0] &] // Length
Select[spec, -1 < # < 0 &] // Length
it gets considerably faster on large lists.
$\endgroup$
Jun 24, 2017 at 10:27
SeedRandom[1];
spec = RandomReal[{-2, 2}, 100000];
Length@Cases[spec, x_ /; -1 < x < 0]
25288