Effacer les filtres
Effacer les filtres

Eliminate repetition in rows addition

1 vue (au cours des 30 derniers jours)
muhammad muda
muhammad muda le 29 Mai 2019
Modifié(e) : Adam Danz le 30 Mai 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

Réponse acceptée

Adam Danz
Adam Danz le 29 Mai 2019
Modifié(e) : Adam Danz le 30 Mai 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

Plus de réponses (0)

Catégories

En savoir plus sur MATLAB dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by