How to reshape a matrix

조회 수: 10 (최근 30일)
Joakim Mørk
Joakim Mørk 2020년 3월 18일
댓글: Joakim Mørk 2020년 3월 18일
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?

답변 (3개)

John D'Errico
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
  댓글 수: 1
Joakim Mørk
Joakim Mørk 2020년 3월 18일
Thank you very much John!! you made my day!. i see what you mean with 'reshape' but it was more literally meant than of Matlab vocab :) but thanks ones more :)

댓글을 달려면 로그인하십시오.


Adam Danz
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

David Hill
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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by