How to reshape a matrix
10 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (3)
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
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
0 comentarios
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
0 comentarios
Ver también
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!