Organize the logic to transform given matrix into required:
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Muhammad Taha
am 23 Jan. 2022
Kommentiert: John D'Errico
am 23 Jan. 2022
Givien[1 2 3
4 5 6
7 8 9]
Reqried[-1 2 3
0 -1 6
0 0 -1]
0 Kommentare
Akzeptierte Antwort
Voss
am 23 Jan. 2022
Bearbeitet: Voss
am 23 Jan. 2022
A = reshape(1:9,3,[]).'
B = triu(A);
B(1:size(A,1)+1:end) = -1
3 Kommentare
Voss
am 23 Jan. 2022
Bearbeitet: Voss
am 23 Jan. 2022
That statement sets the elements along the diagonal of B to be -1.
C = magic(6)
C(1:size(C,1)+1:end)
C(1:size(C,1)+1:end) = 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(1:end) % all elements by linear index
C([1 5 9]) % diagonal elements
C(1:4:end) % same
You could also use eye(), the identity matrix function:
eye(3)
C(logical(eye(3)))
C(logical(eye(3))) = -1
John D'Errico
am 23 Jan. 2022
You could also have done in a slightly simpler way:
A = reshape(1:9,3,[]).'
B = triu(A,1) - eye(size(A))
Thus triu (and tril) with a second argument, allows you to control which diagonal to go to.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Operating on Diagonal Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!