Summing up values of A matrix if it matches the same value in B

1 回表示 (過去 30 日間)
JL
JL 2019 年 8 月 27 日
コメント済み: JL 2019 年 8 月 27 日
Hi everyone, I have 2 matrices A and B
A =[1;
2;
1;
3;
4;
5;
6;];
B = [40.5511;
40.5511;
34.6732;
34.6731;
32.1111;
32.1111;
32.1111;]
I want to create C by summing up the values in A if they have the same corresponding value in B.
C = [3 40.5511;
1 34.6732;
3 34.6731;
15 32.1111;];

採用された回答

Alex Mcaulley
Alex Mcaulley 2019 年 8 月 27 日
One option:
[G,ID] = findgroups(B);
C = [splitapply(@sum,A,G),ID]
C =
15.0000 32.1111
3.0000 34.6731
1.0000 34.6732
3.0000 40.5511
  4 件のコメント
Alex Mcaulley
Alex Mcaulley 2019 年 8 月 27 日
You can change the visualization of your command window using format. Do you mean this?
format short
C =
15.0000 32.1111
3.0000 34.6731
1.0000 34.6732
3.0000 40.5511
format long
C =
15.000000000000000 32.111100000000000
3.000000000000000 34.673099999999998
1.000000000000000 34.673200000000001
3.000000000000000 40.551099999999998
JL
JL 2019 年 8 月 27 日
thanks!

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by