有没有办法让matlab根据指定的bin对数组进行求和而不是迭代?如果有建立功能,那就最好了

Ton*_*ony 4 matlab sum histogram

例如,如果

A = [7,8,1,1,2,2,2]; % the bins (or subscripts)
B = [2,1,1,1,1,1,2]; % the array
Run Code Online (Sandbox Code Playgroud)

然后所需的功能"binsum"有两个输出,一个是箱子,另一个是总和.它只是根据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]
Run Code Online (Sandbox Code Playgroud)

"箱"中的元素不需要排序,但必须与"总和"中的元素相对应.这肯定可以通过"for"迭代来完成,但是不希望"for"迭代,因为存在性能问题.最好是为此建立功能.

非常感谢!

bea*_*ker 5

这是另一项工作 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);
Run Code Online (Sandbox Code Playgroud)

结果:

>> bins
bins =

   1   2   7   8

sums =

   2   4   0   0   0   0   2   1
Run Code Online (Sandbox Code Playgroud)

索引in sums对应于bin值,所以sums(2) = 4.您可以使用nonzeros删除未使用的箱子,以便bins(n)对应sums(n)

sums = nonzeros(sums).';

sums =

   2   4   2   1
Run Code Online (Sandbox Code Playgroud)

或者,sums在一行中生成这种形式:

sums = nonzeros(accumarray(A.', B.')).';
Run Code Online (Sandbox Code Playgroud)


Lui*_*ndo 5

另一种可能性是使用sparse然后find.