Finding frequency of range of numbers in Mathematica

回眸只為那壹抹淺笑 提交于 2019-11-30 21:29:47

The most direct way is simply:

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

There are however much faster ways for most data, this one thanks to Carl Woll:

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

Carl Woll's method is particularly fast, but as yoda pointed out, it fails if your list contains zeros, and your range also straddles 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-#)]&

Here is one approach that 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 alternate approach using IntervalMemberQ is

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

another approach is

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

D

Please look into BinCount:

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

Out[176]= {4}

Compare with direct count:

In[177]:= Count[Range[30], x_ /; 2 <= x < 11/2]

Out[177]= 4
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!