How to reshape a matrix

10 views (last 30 days)
Joakim Mørk
Joakim Mørk on 18 Mar 2020
Commented: Joakim Mørk on 18 Mar 2020
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?

Answers (3)

John D'Errico
John D'Errico on 18 Mar 2020
Edited: John D'Errico on 18 Mar 2020
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 Comment
Joakim Mørk
Joakim Mørk on 18 Mar 2020
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 :)

Sign in to comment.


Adam Danz
Adam Danz on 18 Mar 2020
Edited: Adam Danz on 18 Mar 2020
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 on 18 Mar 2020
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

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!