例如,如果

A = [7,8,1,1,2,2,2]; % the bins (or subscripts)
B = [2,1,1,1,1,1,2]; % the array

那么所需的函数“binsum”有两个输出,一个是bins,另一个是sum。它只是根据A中的下标将B中的值相加。 例如,对于2,总和为1 + 1 + 2 = 4,对于1则为1 + 1 = 2。
[bins, sums] = binsum(A,B);

bins = [1,2,7,8]
sums = [2,4,2,1]

“bins”中的元素不需要排序,但必须对应于“sums”中的元素。这当然可以通过“for”迭代来完成,但是 “for”迭代不是所期望的 ,因为存在性能问题。最好有一个内置函数。

非常感谢!

最佳答案

这是 accumarray 的另一份工作

A = [7,8,1,1,2,2,2]; % the bins (or subscripts)
B = [2,1,1,1,1,1,2]; % the array

sums = accumarray(A.', B.').';
bins = unique(A);

结果:
>> bins
bins =

   1   2   7   8

sums =

   2   4   0   0   0   0   2   1
sums 中的索引对应于 bin 值,因此 sums(2) = 4 。您可以使用 nonzeros 删除未使用的 bin,以便 bins(n) 对应 sums(n)
sums = nonzeros(sums).';

sums =

   2   4   2   1

或者,在一行中生成这种形式的 sums:
sums = nonzeros(accumarray(A.', B.')).';

关于matlab - matlab有什么方法可以根据指定的bin对数组求和而不是迭代?最好有内置功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45661195/

10-13 01:55