Resize a matrix into another with different size

Hello, i got a matrix X and I want to transform X into a matrix rows x collumns, in this case into a 4 by 7 matrix. I used reshape but it doesnt work because of the 2 nans i must create i assume.
k = 26;
X = [1:k]';
[n,m] = size(X);
rows = 4;
columns = ceil(n/rows);
Into something like that, if possible:
x(1) x(5) x(9) x(13) x(17) x(21) x(25)
x(2) x(6) x(10) x(14) x(18) x(22) x(26)
x(3) x(7) x(11) x(15) x(19) x(23) NaN
x(4) x(8) x(12) x(16) x(20) x(24) NaN

 Respuesta aceptada

Matt J
Matt J el 26 de Nov. de 2018
Editada: Matt J el 26 de Nov. de 2018
extra = rows*ceil(numel(X)/rows) - numel(X);
reshape([X(:);nan(extra,1)],rows,columns)

3 comentarios

Tiago Dias
Tiago Dias el 26 de Nov. de 2018
this one doesnt work
Error using horzcat
Dimensions of matrices being concatenated are not consistent.
Error in ES5 (line 25)
reshape([X(:),nan(extra,1)],rows,columns)
Stephen23
Stephen23 el 26 de Nov. de 2018
([X(:);nan(extra,1)]
^ needs a semicolon here!
Tiago Dias
Tiago Dias el 26 de Nov. de 2018
Thanks for your help!

Iniciar sesión para comentar.

Más respuestas (2)

Luna
Luna el 26 de Nov. de 2018
Editada: Luna el 26 de Nov. de 2018
Hi,
Try this:
k = 26;
X = [1:k]';
[n,m] = size(X);
rows = 4;
columns = ceil(n/rows);
X(numel(X):(rows*columns)) = NaN;
reshape(X,rows,columns)

1 comentario

Tiago Dias
Tiago Dias el 26 de Nov. de 2018
Editada: Tiago Dias el 26 de Nov. de 2018
this one works 95% i would say, the number 26 doesnt show up :/
ans =
1 5 9 13 17 21 25
2 6 10 14 18 22 NaN
3 7 11 15 19 23 NaN
4 8 12 16 20 24 NaN
I tried this and i think it works
extra_row = rows * columns;
X(n+1:extra_row) = NaN;
X_new = reshape(X,rows,columns)

Iniciar sesión para comentar.

Stephen23
Stephen23 el 26 de Nov. de 2018
Editada: Stephen23 el 26 de Nov. de 2018

1 voto

A simpler solution:
>> X = 1:26;
>> R = 4;
>> N = numel(X);
>> M = nan(R,ceil(N/R));
>> M(1:N) = X
M =
1 5 9 13 17 21 25
2 6 10 14 18 22 26
3 7 11 15 19 23 NaN
4 8 12 16 20 24 NaN

Categorías

Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 26 de Nov. de 2018

Editada:

el 26 de Nov. de 2018

Community Treasure Hunt

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

Start Hunting!

Translated by