How to reshape a matrix

10 visualizaciones (últimos 30 días)
Joakim Mørk
Joakim Mørk el 18 de Mzo. de 2020
Comentada: Joakim Mørk el 18 de Mzo. de 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?

Respuestas (3)

John D'Errico
John D'Errico el 18 de Mzo. de 2020
Editada: John D'Errico el 18 de Mzo. de 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 comentario
Joakim Mørk
Joakim Mørk el 18 de Mzo. de 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 :)

Iniciar sesión para comentar.


Adam Danz
Adam Danz el 18 de Mzo. de 2020
Editada: Adam Danz el 18 de Mzo. de 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 el 18 de Mzo. de 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

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by