使用accumarray在Matlab中对数据求和

时间:2014-07-20 05:40:04

标签: matlab matrix accumarray

我有一个像这样的矩阵:

>>D=[1,0,10;3,1,12;3,1,12.5;6,1,6;6,2,11.1;]
D =

1.0000         0   10.0000
3.0000    1.0000   12.0000
3.0000    1.0000   12.5000
6.0000    1.0000    6.0000
6.0000    2.0000   11.1000

如果第一列的数据相同,我想得到第二列数据的总和。例如,我想:

E=
1.0000         0
3.0000    2.0000
6.0000    3.0000

所以我试过

b = accumarray(D(:,1),D(:,2),[],[],[],true);
[i,~,v] = find(b);
E = [i,v]

但它没有用。我该怎么办?

1 个答案:

答案 0 :(得分:5)

以这种方式组合uniqueaccumarray -

[unique_ids,~,idmatch_indx] = unique(D(:,1)); 
%// unique_ids would have the unique numbers from first column and only 
%// used to get the first column of final output, E. 
%// idmatch_indx are tags put on each element corresponding to each unique_ids
%// based on the uniqueness

%// Accumulate and perform summation of elements from second column of D using
%// subscripts from idmatch_indx
E = [unique_ids accumarray(idmatch_indx,D(:,2))]

对于accumarray,您通常需要输入要在累积元素上使用的函数,但@sum是默认的函数句柄,您可以省略此情况。< / p>