Eliminate repetition in rows addition

2 ビュー (過去 30 日間)
muhammad muda
muhammad muda 2019 年 5 月 29 日
編集済み: Adam Danz 2019 年 5 月 30 日
Hi,
How to eliminate repetitions that happen in this rows addition? I am adding the numbers in row 1 and 2, row 1 and 3 and row 2 and 3.
The matrix is:
A =
3 10
5 6
7 8
And after running this code this is what I get:
B =
26 24 28
24 22 26
28 26 30
How to make it more efficient, since I do not need to repeat the same addition (i.e. row 2 and 1) and self addition (row 1 and 1). I should get B like this:
B =
0 24 28
0 0 26
0 0 0
Any idea?
A = [3 10; 5 6; 7 8];
for i = 1:3
for j = 1:3
Ai = A(i,:);
Aj = A(j,:);
result = 0;
for k = 1:2
result = result + Ai(k) + Aj(k);
end
B(i,j) = result;
end
end
B

採用された回答

Adam Danz
Adam Danz 2019 年 5 月 29 日
編集済み: Adam Danz 2019 年 5 月 30 日
You can replace those loops with this:
A = [3 10; 5 6; 7 8];
triu(sum(A,2)+sum(A,2)',1)
ans =
0 24 28
0 0 26
0 0 0
If you want to retain the diagonal,
triu(sum(A,2)+sum(A,2)')
ans =
26 24 28
0 22 26
0 0 30

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by