필터 지우기
필터 지우기

Eliminate repetition in rows addition

조회 수: 1 (최근 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 CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by