Organize the logic to transform given matrix into required:

1 view (last 30 days)
Muhammad Taha
Muhammad Taha on 23 Jan 2022
Commented: John D'Errico on 23 Jan 2022
Givien[1 2 3
4 5 6
7 8 9]
Reqried[-1 2 3
0 -1 6
0 0 -1]

Accepted Answer

_
_ on 23 Jan 2022
Edited: _ 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
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)

Community Treasure Hunt

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

Start Hunting!