4

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

Peter Mortensen
  • 759
  • 4
  • 7
clive elphick
  • 561
  • 2
  • 6

5 Answers5

10
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] &} ]

Mathematica graphics

For SeedRandom[1];s = RandomReal[{-2, 2}, 10^7]; we get:

Mathematica graphics

Note: Still on version 9, so cannot include CountsBy in the timings table.

kglr
  • 394,356
  • 18
  • 477
  • 896
4
Total[Boole[-1 <= # <= 0] & /@ spec]
ubpdqn
  • 60,617
  • 3
  • 59
  • 148
3
SeedRandom[1]
spec = RandomReal[{-2, 2}, 100];

CountsBy[spec, -1 <= # <= 0 &]

enter image description here

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}

eldo
  • 67,911
  • 5
  • 60
  • 168
1
Select[spec, And[# > -1, # < 0] &] // Length
Morgan
  • 525
  • 2
  • 10
1
SeedRandom[1];
spec = RandomReal[{-2, 2}, 100000];

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

25288

aardvark2012
  • 5,424
  • 1
  • 11
  • 22