Repmat the rows of a matrix
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Dear;
I would like to efficiently repmat the rows of a matrix to for a new one; For example the matrix:
A=[2 0 0;
0 2 0;
0 0 2;
];
I want to replicate 3 times the rows to form the following matrix:
B=[2 0 0;
2 0 0;
2 0 0;
0 2 0;
0 2 0;
0 2 0;
0 0 2;
0 0 2;
0 0 2;
];
Is there any vectorized way to perform this operation (without using for loops).
Thanks in advance;
0 comentarios
Respuestas (2)
Jordan Lui
el 2 de Dic. de 2020
Be careful with the other answer. It will not work for more general cases. Instead, try this:
numRep = 3;
[r,c] = size(A);
B1 = repmat(A', numRep , 1);
B = reshape(B1, [], r * numRep)';
0 comentarios
Star Strider
el 20 de En. de 2016
This works:
A=[2 0 0;
0 2 0;
0 0 2];
[Ar,Ac] = size(A);
B1 = repmat(A, Ar, 1);
B = reshape(B1, [], size(B1,1))'
B =
2 0 0
2 0 0
2 0 0
0 2 0
0 2 0
0 2 0
0 0 2
0 0 2
0 0 2
1 comentario
Jordan Lui
el 2 de Dic. de 2020
This solution does not work on an example like this:
A=[2 7 8;
4 2 8;
5 6 2
-1 -1 -1;
];
Using a non square matrix and filling the off diagonals shows the issue. Result will be:
B =
2 4 5
-1 2 4
5 -1 2
4 5 -1
2 4 5
-1 7 2
6 -1 7
2 6 -1
7 2 6
-1 7 2
6 -1 8
8 2 -1
8 8 2
-1 8 8
2 -1 8
8 2 -1
The following solution works:
numRep = 3;
[r,c] = size(A);
B1 = repmat(A', numRep , 1);
B = reshape(B1, [], r * numRep)';
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!