Organize the logic to transform given matrix into required:

조회 수: 1 (최근 30일)
Muhammad Taha
Muhammad Taha 2022년 1월 23일
댓글: John D'Errico 2022년 1월 23일
Givien[1 2 3
4 5 6
7 8 9]
Reqried[-1 2 3
0 -1 6
0 0 -1]

채택된 답변

Voss
Voss 2022년 1월 23일
편집: Voss 2022년 1월 23일
A = reshape(1:9,3,[]).'
A = 3×3
1 2 3 4 5 6 7 8 9
B = triu(A);
B(1:size(A,1)+1:end) = -1
B = 3×3
-1 2 3 0 -1 6 0 0 -1
  댓글 수: 3
Voss
Voss 2022년 1월 23일
편집: Voss 2022년 1월 23일
That statement sets the elements along the diagonal of B to be -1.
C = magic(6)
C = 6×6
35 1 6 26 19 24 3 32 7 21 23 25 31 9 2 22 27 20 8 28 33 17 10 15 30 5 34 12 14 16 4 36 29 13 18 11
C(1:size(C,1)+1:end)
ans = 1×6
35 32 2 17 14 11
C(1:size(C,1)+1:end) = 1000
C = 6×6
1000 1 6 26 19 24 3 1000 7 21 23 25 31 9 1000 22 27 20 8 28 33 1000 10 15 30 5 34 12 1000 16 4 36 29 13 18 1000
It is using linear indexing, which in MATLAB goes down the columns first. Starting with index 1 (the upper-left), incrementing by one more than the number of rows gives you the index of each element along the diagonal.
C = magic(3)
C = 3×3
8 1 6 3 5 7 4 9 2
C(1:end) % all elements by linear index
ans = 1×9
8 3 4 1 5 9 6 7 2
C([1 5 9]) % diagonal elements
ans = 1×3
8 5 2
C(1:4:end) % same
ans = 1×3
8 5 2
You could also use eye(), the identity matrix function:
eye(3)
ans = 3×3
1 0 0 0 1 0 0 0 1
C(logical(eye(3)))
ans = 3×1
8 5 2
C(logical(eye(3))) = -1
C = 3×3
-1 1 6 3 -1 7 4 9 -1
John D'Errico
John D'Errico 2022년 1월 23일
You could also have done in a slightly simpler way:
A = reshape(1:9,3,[]).'
A = 3×3
1 2 3 4 5 6 7 8 9
B = triu(A,1) - eye(size(A))
B = 3×3
-1 2 3 0 -1 6 0 0 -1
Thus triu (and tril) with a second argument, allows you to control which diagonal to go to.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by