Add a diagonal of zeros to a matrix in MATLAB

24 ビュー (過去 30 日間)
Amal FH
Amal FH 2020 年 12 月 25 日
コメント済み: Amal FH 2020 年 12 月 25 日
Let
M1 = [ 1 2 3 4
2 5 4 2
3 4 5 1
4 2 1 2 ]
a diagonal matrix.
I want to add a diagonal of zeros where
M1'= [ 0 1 2 3 4
1 0 5 4 2
2 5 0 5 1
3 4 5 0 2
4 2 1 2 0 ]
So I keep the original matrix and just add the diagonal of zeros. So size(M1) = (4x4) ans size (M1')=(5x5)
I tried "
M1' = [tril(M1,-1) zeros(N, 1)] + [zeros(N,1) triu(M1)];
" But this won't work because it changes the diagonal of the original matrix.
  1 件のコメント
Amal FH
Amal FH 2020 年 12 月 25 日
I meant a symmetric matrix.

サインインしてコメントする。

採用された回答

Asad (Mehrzad) Khoddam
Asad (Mehrzad) Khoddam 2020 年 12 月 25 日
You can use a loop like this:
M1 = [ 1 2 3 4
2 5 4 2
3 4 5 1
4 2 1 2 ];
N=size(M1,1);
M2=zeros(N+1,N+1);
for i=0:N-1
M2 = M2 + diag(diag(M1,-i),-i-1)+ diag(diag(M1,i),i+1);
end
M2
  1 件のコメント
Amal FH
Amal FH 2020 年 12 月 25 日
Thank you so much!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by