Diagonal of non-square matrix

8 ビュー (過去 30 日間)
Shuqing Qi
Shuqing Qi 2021 年 4 月 27 日
コメント済み: Shuqing Qi 2021 年 4 月 27 日
How can I build this matrix? All elements are zero except those three main diagonals. n is any given number.

採用された回答

Matt J
Matt J 2021 年 4 月 27 日
n=8;
R=[2,3,4,zeros(1,n+2-3)];
C=[2,zeros(1,n-1)];
T=toeplitz(C,R)
T = 8×10
2 3 4 0 0 0 0 0 0 0 0 2 3 4 0 0 0 0 0 0 0 0 2 3 4 0 0 0 0 0 0 0 0 2 3 4 0 0 0 0 0 0 0 0 2 3 4 0 0 0 0 0 0 0 0 2 3 4 0 0 0 0 0 0 0 0 2 3 4 0 0 0 0 0 0 0 0 2 3 4
  1 件のコメント
Shuqing Qi
Shuqing Qi 2021 年 4 月 27 日
Thank you!

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

その他の回答 (2 件)

Bruno Luong
Bruno Luong 2021 年 4 月 27 日
編集済み: Bruno Luong 2021 年 4 月 27 日
n = 8;
A = spdiags([2 3 4]+zeros(n,1),0:2,n,n+2);
A = full(A) % if prefered
A = 8×10
2 3 4 0 0 0 0 0 0 0 0 2 3 4 0 0 0 0 0 0 0 0 2 3 4 0 0 0 0 0 0 0 0 2 3 4 0 0 0 0 0 0 0 0 2 3 4 0 0 0 0 0 0 0 0 2 3 4 0 0 0 0 0 0 0 0 2 3 4 0 0 0 0 0 0 0 0 2 3 4
  1 件のコメント
Shuqing Qi
Shuqing Qi 2021 年 4 月 27 日
Thank you!

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


Clayton Gotberg
Clayton Gotberg 2021 年 4 月 27 日
編集済み: Clayton Gotberg 2021 年 4 月 27 日
n = 5; % Example input
diagonals = [2 3 4];
% Method 1:
matrix = zeros(n,n+2); % Preallocate for speed
extra_zeros = zeros(1,n-1);
matrix_row = [diagonals extra_zeros];
for k = 1:n
matrix(k,:) = matrix_row;
matrix_row = circshift(matrix_row,1);
end
% Method 2:
diagonal_one = [diag(repmat(diagonals(1),n,1)) zeros(n,2)];
diagonal_two = [zeros(n,1) diag(repmat(diagonals(2),n,1)) zeros(n,1)];
diagonal_three = [zeros(n,2) diag(repmat(diagonals(3),n,1))];
matrix = diagonal_one+diagonal_two+diagonal_three;
The second method is a little faster.
  1 件のコメント
Shuqing Qi
Shuqing Qi 2021 年 4 月 27 日
Thank you!

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

カテゴリ

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