【问题标题】:A combination of hist and sum:is there a function for that?hist 和 sum 的组合:有这个功能吗?
【发布时间】:2012-04-12 23:53:29
【问题描述】:

假设我们有以下向量:

data=a=[2.3 3.2 4.1 6.2 7.3 6.4 5.5 4.3 3.2 2.6 1.7 3.4 4.5 5.7 6.8];

如果我们只使用 hist 函数来计算数字,我们会得到类似的结果:

[n xout]=hist(a,[1:1:max(a)])

n =

 0     0     2     4     3     1     3     2

xout =

 0     1     2     3     4     5     6     7

我现在要做的是对 bin 的每个元素求和:

xout =

 0     1     2     3     4     5     6     7

n =

 0     0     2     4     3     1     3     2

binsum =

0      0     4    12.4 etc.

例如,对于第三个 bin,我的 n(3)=2 值介于 1,5 和 2,5(bin 的大小)之间:1.7 和 2.3 -> 1.7+2.3=4 -> binsum(3 )=4 对于第四个 bin,我的 n(4)=4 值介于 2,5 和 3,5 之间:3.2+3.2+3.4+2.6=12.4-> binsum(4)=12.4 等。

是否有一个简单的功能可以完成这项工作?

【问题讨论】:

    标签: matlab sum histogram


    【解决方案1】:

    如果你的直方图 bin 是由数组 minBin:binWidth:maxBin 定义的,那么你可以找到 bin 的索引,然后像这样总结数据:

    minBin = 1;
    binWidth = 1;
    maxBin = 7;
    
    data=[2.3 3.2 4.1 6.2 7.3 6.4 5.5 4.3 3.2 2.6 1.7 3.4 4.5 5.7 6.8];
    
    %# to create index: First, take care of out-of-range data points
    tmp = max(min( data, maxBin),minBin);
    %# then, subtract minimum, divide by step, round: this is the binIdx
    %# add 1 so that we don't start counting at 0
    idx = round( (tmp-minBin)/binWidth ) +1;
    
    %# now we can use accumarray to sum up the data
    binSum = accumarray(idx(:),data(:),[floor((maxBin-minBin)/binWidth)+1, 1], @sum, 0)
    
    binSum =
    
             0
        4.0000
       12.4000
        8.4000
        4.5000
       23.8000
       14.1000
    

    请注意,我没有先得到两个零,因为我使用您用作hist 输入的箱,而不是您显然用来生成输出的箱。此外,您可以通过将data 替换为ones(length(data),1) 来获取计数。

    【讨论】:

      猜你喜欢
      • 2013-03-22
      • 2011-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      • 1970-01-01
      • 2019-10-24
      • 1970-01-01
      相关资源
      最近更新 更多