How to add up numbers with same value in matlab

前端 未结 1 427
失恋的感觉
失恋的感觉 2021-01-16 17:47

So if i have an number array:

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

i want to sum up numbers in column a with

1条回答
  •  攒了一身酷
    2021-01-16 18:07

    Assuming A to be the input array, you have two approaches to play with here.

    Approach #1

    A combination of accumarray and unique -

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

    Approach #2

    With bsxfun -

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

    0 讨论(0)
提交回复
热议问题