matlab如何将相同值的数相加

How to add up numbers with same value in matlab

所以如果我有一个数字数组:

a     b
1     2.5 
1     1.2 
3     2.5
4     0.4
6     3
3     1.2

我想将 a 列中的数字与第 2 列中的 b 的相同值相加,如下所示:

a   b
4   2.5 
4   1.2 
4   0.4
6   3

所以你可以看到 1 和 3 加起来变成 4,因为它们具有相同的 b 值,即 2 和其余数字,所以我将如何做到这一点?谢谢 (PS:我的真实数据是整数和小数的组合,谢谢)

假设 A 是输入数组,您可以使用两种方法。

方法 #1

accumarray and unique-

的组合
[unqcol2,~,idx] = unique(A(:,2),'stable')
[accumarray(idx,A(:,1)) unqcol2]

方法 #2

bsxfun-

[unqcol2,~,idx] = unique(A(:,2),'stable')
[sum(bsxfun(@times,bsxfun(@eq,idx,1:max(idx)),A(:,1)),1).' unqcol2 ]