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 个评论
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