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...
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...
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.
Count is a pattern (see Count), while the second argument of Select is a boolean function (see Select)
– kglr
Jun 24 '17 at 12:12
Total[Boole[-1 <= # <= 0] & /@ spec]
Unitize and didn't think. Thanks :)
– ubpdqn
Jun 24 '17 at 11:36
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.
– aardvark2012
Jun 24 '17 at 10:27
SeedRandom[1];
spec = RandomReal[{-2, 2}, 100000];
Length@Cases[spec, x_ /; -1 < x < 0]
25288