How to add a diagonal to a matrix?

조회 수: 1 (최근 30일)
Nadia_Ny635
Nadia_Ny635 2020년 9월 4일
댓글: Matt J 2020년 9월 4일
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?

답변 (1개)

Matt J
Matt J 2020년 9월 4일
편집: Matt J 2020년 9월 4일
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
Nadia_Ny635
Nadia_Ny635 2020년 9월 4일
Thank you so much
Matt J
Matt J 2020년 9월 4일
You're quite welcome, but please Accept-click the answer if it resolves your question.

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

카테고리

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