How to add values in matrix if in a conditions is met?

7 ビュー (過去 30 日間)
Danny Helwegen
Danny Helwegen 2020 年 12 月 8 日
編集済み: dpb 2020 年 12 月 8 日
Hey everybody,
I'm processing some data and i'm stuck at the moment. I have a matrix consisting of 2 columns and about 4000 rows. A simplified example is given below:
data = 0 1.5
0.2 0.3
0.4 4
0.6 0.2
0.8 0.9
1 1.5
0 2
0.2 1.2
0.4 0.8
0.6 2.3
0.8 4.5
1 1.3
And what I need is that when values in column 1 are the same, then values of the second column are added to get one answer for one value in column 1. For the data above this would give:
For 0: 1.5 + 2 = 3.5
0.2: 0.3 + 1.2 = 1.5
0.4: 4 + 0.8 = 4.8
etc.
Could anyone help me with how to do this? Cause at the moment, I really don't know how. I tried a if loop but it didn't work.

採用された回答

dpb
dpb 2020 年 12 月 8 日
編集済み: dpb 2020 年 12 月 8 日
>> accumarray(findgroups(data(:,1)),data(:,2))
ans =
3.5000
1.5000
4.8000
2.5000
5.4000
2.8000
>>
or, more completely
>> [ig,g]=findgroups(data(:,1));
>> [g accumarray(ig,data(:,2))]
ans =
0 3.5000
0.2000 1.5000
0.4000 4.8000
0.6000 2.5000
0.8000 5.4000
1.0000 2.8000
>>

その他の回答 (1 件)

Ze-Zheng Wu
Ze-Zheng Wu 2020 年 12 月 8 日
splitapply(@(x) [x(1, 1), sum(x(:, 2))], data, findgroups(data(:, 1)));
  2 件のコメント
Danny Helwegen
Danny Helwegen 2020 年 12 月 8 日
Thanks for the reply, if I run this I get als negative values whilst I don't have them in my data set. Any idea how I can solve that?
Ze-Zheng Wu
Ze-Zheng Wu 2020 年 12 月 8 日
This piece of code works just fine with your example data:
data = [0 1.5;
0.2 0.3;
0.4 4 ;
0.6 0.2;
0.8 0.9 ;
1 1.5;
0 2;
0.2 1.2;
0.4 0.8;
0.6 2.3;
0.8 4.5;
1 1.3];
splitapply(@(x) [x(1, 1), sum(x(:, 2))], data, findgroups(data(:, 1)))
ans =
0 3.5000
0.2000 1.5000
0.4000 4.8000
0.6000 2.5000
0.8000 5.4000
1.0000 2.8000
I'm not sure how can there be negative values.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by