How to add zeros diagonally in a matrix?
조회 수: 4 (최근 30일)
이전 댓글 표시
I am having a 4*5 matrix. Now, I need to add '0' diagonally and convert the matrix into 5*5. Thank you in advance.
Example:
A=[2 2 1 3 2
1 3 3 1 2
3 1 4 4 1
2 2 1 3 3]
Expected output:
B=[ 0 2 1 3 2
2 0 3 1 2
1 3 0 4 1
3 1 4 0 3
2 2 1 3 0]
댓글 수: 0
채택된 답변
Stephen23
2022년 12월 14일
A = [2,2,1,3,2;1,3,3,1,2;3,1,4,4,1;2,2,1,3,3]
S = size(A)+[1,0];
B = zeros(S);
B(~eye(S)) = A
추가 답변 (1개)
Jiri Hajek
2022년 12월 14일
Hi, MATLAB has functions that can extract upper and lower triangular parts of a matric, rest is just adding them into a zero pre-allocated matrix B:
A = randn(4)
Au = triu(A);
Al = tril(A);
B = zeros(5);
B(1:4,2:end) = Au;
B(2:end,1:4) = B(2:end,1:4)+Al
참고 항목
카테고리
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!