Finding a frequency range for numbers in Mathematica

Given the list of numbers in Mathematica, how would I extract from this list the total number of numbers between the numbers a and b that I specify?

+6
source share
4 answers

The most direct way is simply:

 Count[data, x_ /; a <= x <= b] 

However, for most data, there are much faster ways, thanks to Karl Woll:

 Tr@Unitize @Clip[data, {a, b}, {0, 0}] 

Karl Wall's method is especially fast, but, as Yoda pointed out, it fails if your list contains zeros and your range also oscillates to zero. Here is another method from Kevin J. McCann that handles this case and is still very fast:

 Tr@UnitStep [(data - a)*(b - data)] 

As a pure function [data, a, b]:

 Tr@UnitStep [(#-#2)*(#3-#)]& 
+10
source

Here is one way you can try:

 freq[a_, b_, list_] := Total@Boole @Cases[list, x_ :> a <= x <= b] lst = RandomInteger[10, 20] Out = {6, 1, 1, 6, 3, 1, 10, 0, 2, 10, 3, 5, 9, 1, 5, 5, 3, 8, 2, 3} freq[3, 6, lst] Out = 9 

An alternative approach using IntervalMemberQ is

 freq[a_, b_, list_] := Total@Boole @IntervalMemberQ[Interval[{a, b}], list] 
+2
source

different approach

 NumberOfNumbers[lst_?ListQ, lwr_?NumberQ, upr_?NumberQ] := Length@Select [lst, (lwr <= # <= upr) &] 

D

+1
source

Please view BinCount :

 In[176]:= BinCounts[Range[30], {{2, 11/2}}] Out[176]= {4} 

Compare with direct calculation:

 In[177]:= Count[Range[30], x_ /; 2 <= x < 11/2] Out[177]= 4 
+1
source

Source: https://habr.com/ru/post/888284/


All Articles