Clear Filters
Clear Filters

Eliminate repetition in rows addition

1 view (last 30 days)
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

Accepted Answer

Adam Danz
Adam Danz on 29 May 2019
Edited: Adam Danz on 30 May 2019
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

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!