在Mathematica中查找数字范围的频率

时间:2011-05-17 05:59:16

标签: wolfram-mathematica

鉴于Mathematica中的数字列表,我如何从该列表中提取我指定的数字ab之间的总数?

4 个答案:

答案 0 :(得分:10)

最直接的方法是:

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

大多数数据都有更快的方法,这要归功于Carl Woll:

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

Carl Woll的方法特别快,但正如yoda所指出的,如果你的列表中包含零,它就会失败,你的范围也会超过零。这是Kevin J. McCann处理这种情况的另一种方法,但仍然非常快:

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

作为纯函数[data,a,b]:

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

答案 1 :(得分:2)

您可以尝试以下方法:

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

使用IntervalMemberQ的替代方法是

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

答案 2 :(得分:1)

另一种方法是

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

d

答案 3 :(得分:1)

请查看BinCount

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

Out[176]= {4}

与直接计数比较:

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

Out[177]= 4
相关问题