# Counting numbers in a range in a vector

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

• Old duplicate on Stack Overflow: (6026827). Related: (9637) Commented Jul 1, 2017 at 14:13

## 5 Answers

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.

• Great, but why is the condition syntax different from Select []? Commented Jun 24, 2017 at 12:00
• @Morgan, The second argument of Count is a pattern (see Count), while the second argument of Select is a boolean function (see Select)
– kglr
Commented Jun 24, 2017 at 12:12
• @Morgan see (18054), (88220) Commented Jul 1, 2017 at 14:49
Total[Boole[-1 <= # <= 0] & /@ spec]
• Isn't Unitize redundant? Commented Jun 24, 2017 at 11:33
• @Coolwater d'oh...I have amended. I had an answer that used Unitize and didn't think. Thanks :) Commented Jun 24, 2017 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
• For what it's worth, if you change it to Select[spec, -1 < # < 0 &] // Length it gets considerably faster on large lists. Commented Jun 24, 2017 at 10:27
• Nice, thank you. Commented Jun 24, 2017 at 10:28
SeedRandom[1];
spec = RandomReal[{-2, 2}, 100000];

Length@Cases[spec, x_ /; -1 < x < 0]

25288