我有这样的矩阵:
>>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]
但没起作用。我该怎么办?
发布于 2014-07-20 05:51:27
把unique
和accumarray
结合起来-
[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
是默认的函数句柄,在这种情况下可以忽略它。
https://stackoverflow.com/questions/24847727
复制相似问题