Diagonal of non-square matrix
조회 수: 4 (최근 30일)
이전 댓글 표시
How can I build this matrix? All elements are zero except those three main diagonals. n is any given number.
댓글 수: 0
채택된 답변
추가 답변 (2개)
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
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!