【问题标题】:Using accumarray to sum data in MatlabMatlab中使用accumarray对数据求和
【发布时间】:2014-07-20 15:34:26
【问题描述】:

我有一个这样的矩阵:

>>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]

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

【问题讨论】:

    标签: matlab matrix accumarray


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-06-19
      • 2014-02-03
      • 1970-01-01
      • 2015-07-25
      • 2015-04-12
      • 2013-11-12
      • 2014-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多