Borrar filtros
Borrar filtros

Duplicating rows in a matrix

116 visualizaciones (últimos 30 días)
Edward Johnsen
Edward Johnsen el 23 de En. de 2019
Editada: Stephen23 el 5 de En. de 2022
Hi there
I have a matrix that i need to make twice as long. i.e i need to double the length of columns. eg i need:
[0 1 0 0]
[0 2 0 0]
to become:
[0 1 0 0]
[0 1 0 0]
[0 2 0 0]
[0 2 0 0]
Thanks
  1 comentario
Stephen23
Stephen23 el 3 de En. de 2022
Editada: Stephen23 el 5 de En. de 2022
A = [0,1,0,0;0,2,0,0]
A = 2×4
0 1 0 0 0 2 0 0
B = repelem(A,2,1)
B = 4×4
0 1 0 0 0 1 0 0 0 2 0 0 0 2 0 0

Iniciar sesión para comentar.

Respuesta aceptada

Star Strider
Star Strider el 23 de En. de 2019
Editada: Star Strider el 23 de En. de 2019
Try this:
M = [0 1 0 0
0 2 0 0];
M2 = repmat(M, 1, 2);
M2 = reshape(M2', [], 4)'
producing:
M2 =
0 1 0 0
0 1 0 0
0 2 0 0
0 2 0 0
You could combine both calculations into a one-line calcualtion if you want to.
EDIT —
Generally, for ‘N’ repitions, the code becomes:
N = 4; % Number Of Repititions
Mn = repmat(M, 1, N)
Mn = reshape(Mn', [], 2*N)'
producing:
Mn =
0 1 0 0
0 1 0 0
0 1 0 0
0 1 0 0
0 2 0 0
0 2 0 0
0 2 0 0
0 2 0 0
  3 comentarios
Stephen23
Stephen23 el 3 de En. de 2022
Editada: Stephen23 el 3 de En. de 2022
@Matthew Allison if you think that is elegant, just wait until you see REPELEM in action:
M = [0,1,0,0;0,2,0,0]
M = 2×4
0 1 0 0 0 2 0 0
Mn = repelem(M,2,1)
Mn = 4×4
0 1 0 0 0 1 0 0 0 2 0 0 0 2 0 0
REPELEM was introduced in R2015a, it is not clear why StarStrider avoided using it here.
Star Strider
Star Strider el 3 de En. de 2022
Editada: Star Strider el 4 de En. de 2022
@Matthew Allison — Thank you!
@Stephen — Because I wanted to make it general enough to work with earlier versions as well.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Chemistry en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by