Adding matrices rows having the same id

2 ビュー (過去 30 日間)
Mo H
Mo H 2020 年 3 月 22 日
コメント済み: Adam Danz 2020 年 3 月 22 日
Hello, I would like to sum rows of two matrices if they have the sam id (first column). For instance, I have a matrix A and matrix B:
A = [
1 4 5 6;
2 5 5 3;
3 9 8 2];
B = [
4 5 6 2;
2 9 4 1;
1 5 7 9;
3 5 6 7;
1 4 5 3];
I would like to get matrix C such that it looks at the first column and add the other columns if id is the same in both matrices.
C = [
1 13 17 18;
2 14 9 4;
3 14 14 9;
4 5 6 2];
Thank you
  3 件のコメント
Mo H
Mo H 2020 年 3 月 22 日
Adam provided a great answer, and I hope it is helpful for the community
Adam Danz
Adam Danz 2020 年 3 月 22 日
Thanks for restoring the question and for the compliment, Mohammad.

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

採用された回答

Adam Danz
Adam Danz 2020 年 3 月 22 日
編集済み: Adam Danz 2020 年 3 月 22 日
Assuming A and B have the same number of columns,
AB = [A;B];
C = [unique(AB(:,1)), splitapply(@(x) sum(x,1), AB(:,2:end), AB(:,1))];
Result:
C =
1 13 17 18
2 14 9 4
3 14 14 9
4 5 6 2
  1 件のコメント
Mo H
Mo H 2020 年 3 月 22 日
thank you a lot

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by