如何在Matlab中将具有相同值的数字相加 [英] How to add up numbers with same value in matlab

查看:1336
本文介绍了如何在Matlab中将具有相同值的数字相加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我想对a列中的数字求和,第2列中b的值相同:

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

因此您可以看到1和3相加并变成4,因为它们具有相同的b值,即2和其余的数字,所以我将如何做呢?谢谢 (PS:我的真实数据是整数和十进制数字的组合,谢谢)

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)

推荐答案

假定A为输入数组,您可以在此处使用两种方法.

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

方法1

accumarray


方法2

使用 bsxfun -

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

这篇关于如何在Matlab中将具有相同值的数字相加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆