How to add up numbers with same value in matlab

邮差的信 提交于 2020-01-07 00:45:12

问题


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 same value of of b in column 2, like this:

a   b
4   2.5 
4   1.2 
4   0.4
6   3

so as you can see 1 and 3 add up and became 4, because they have the same value of b which is 2 and also to the rest of the numbers, so how i will do that? thanks (PS: my real data is combination of integers and decimal no. thanks)


回答1:


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 ]


来源:https://stackoverflow.com/questions/36598096/averaging-data-that-have-similar-properties-in-matlab

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!