使用Matlab中的accumarray函数对数据进行求和

3

我有一个类似这样的矩阵:

>>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个回答

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是默认的函数句柄,您可以在这种情况下将其省略。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接