How to add a diagonal to a matrix?

1 view (last 30 days)
Nadia_Ny635
Nadia_Ny635 on 4 Sep 2020
Commented: Matt J on 4 Sep 2020
I have the following matrix M=[1 2 3; 4 5 6 ] and I would like to transform it to the follwowing matrix M=[0 1 2; 3 0 4; 5 6 0].
How to do it? It is how to add a zero diagonal to a predefined matrix?

Answers (1)

Matt J
Matt J on 4 Sep 2020
Edited: Matt J on 4 Sep 2020
One way,
[J,I]=ndgrid(1:size(M,1)+1);
idx=(I~=J);
M = accumarray([I(idx),J(idx)],reshape(M.',[],1))
M =
0 1 2
3 0 4
5 6 0
  2 Comments
Matt J
Matt J on 4 Sep 2020
You're quite welcome, but please Accept-click the answer if it resolves your question.

Sign in to comment.

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!