Organize the logic to transform given matrix into required:

1 view (last 30 days)
Givien[1 2 3
4 5 6
7 8 9]
Reqried[-1 2 3
0 -1 6
0 0 -1]

Accepted Answer

Voss
Voss on 23 Jan 2022
Edited: Voss on 23 Jan 2022
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 Comments
Voss
Voss on 23 Jan 2022
Edited: Voss on 23 Jan 2022
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 on 23 Jan 2022
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Operating on Diagonal Matrices 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!