How to reshape a matrix
조회 수: 10 (최근 30일)
이전 댓글 표시
I need to reshape a Matrix from an [5 x n] matrix into a matrix of [n,0,0,0,0 ; 0,n,0,0,0 ; 0,0,n,0,0 ; 0,0,0,n,0 ; 0,0,0,0,n]
Example:
given the matrix: A = [1,2,3,4 ; 1,2,3,4 ; 1,2,3,4 ; 1,2,3,4 ; 1,2,3,4]
reshaped into:
1 2 3 4 0 0 0 0
0 1 2 3 4 0 0 0
0 0 1 2 3 4 0 0
0 0 0 1 2 3 4 0
0 0 0 0 1 2 3 4
How is this done in a simple way?
댓글 수: 0
답변 (3개)
John D'Errico
2020년 3월 18일
편집: John D'Errico
2020년 3월 18일
This has nothing to do with what in MATLAB is describd as a reshape, since a reshape cannot change the number of elements in the matrix. The function reshape already exists, and is quite useful.
toeplitz([1;zeros(4,1)],[1:4,zeros(1,4)])
ans =
1 2 3 4 0 0 0 0
0 1 2 3 4 0 0 0
0 0 1 2 3 4 0 0
0 0 0 1 2 3 4 0
0 0 0 0 1 2 3 4
toeplitz is a simple way to create that matrix. However, there are many alternatives. You could use diag, or perhaps spdiags. Or, you could create it as a circulant matrix. Lots of ways.
This alternative is a bit of a hack, but perhaps cute with the replicated cumsum:
tril(cumsum(cumsum(eye(5,8),2),2),3)
ans =
1 2 3 4 0 0 0 0
0 1 2 3 4 0 0 0
0 0 1 2 3 4 0 0
0 0 0 1 2 3 4 0
0 0 0 0 1 2 3 4
Adam Danz
2020년 3월 18일
편집: Adam Danz
2020년 3월 18일
I would go with John D'Errico's approach (David Hill 's method is also good) but just to add another approach,
A = [1,2,3,4 ; 1,2,3,4 ; 1,2,3,4 ; 1,2,3,4 ; 1,2,3,4];
nPad = 4; % number of 0s to pad to the end of the 1st row
m = zeros(size(A,1), size(A,2)+nPad);
colIdx = bsxfun(@(x,y)x+y, 1:size(A,2), (0:size(A,2)).');
rowIdx = (1:size(A,1)).' .* ones(1,size(colIdx,2)); % Requires >= matlab r2016b
linIdx = sub2ind(size(m), rowIdx, colIdx);
m(linIdx(:)) = A;
m =
1 2 3 4 0 0 0 0
0 1 2 3 4 0 0 0
0 0 1 2 3 4 0 0
0 0 0 1 2 3 4 0
0 0 0 0 1 2 3 4
댓글 수: 0
David Hill
2020년 3월 18일
Lots of way to do it. Here is one:
a=[1 2 3 4 0 0 0 0];
y=a;
for k=1:4
y=[y;circshift(a,k)];
end
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!