Eliminate repetition in rows addition

1 visualización (últimos 30 días)
muhammad muda
muhammad muda el 29 de Mayo de 2019
Editada: Adam Danz el 30 de Mayo de 2019
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

Respuesta aceptada

Adam Danz
Adam Danz el 29 de Mayo de 2019
Editada: Adam Danz el 30 de Mayo de 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

Más respuestas (0)

Categorías

Más información sobre MATLAB en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by