Expanding a Matrix with Repmat/Reshape?
10 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Cou
el 18 de Ag. de 2017
Respondida: Jan
el 18 de Ag. de 2017
I have two vectors:
x = [3 6 7 10]
y = [2 2 2 4]
I am trying to create vector
z = [3 3 6 6 7 7 10 10 10 10]
So each element x(i) is repeated y(i) times. This is straight forward with a for loop, but I'm trying to avoid looping, if possible. The size and values of x and y may change as well (they are populated by variables).
Here's the loop version:
z= [];
for i = 1:numel(y)
z= [z, repmat(x(i), 1, y(i))];
end
Any help is appreciated.
0 comentarios
Respuesta aceptada
James Tursa
el 18 de Ag. de 2017
Editada: James Tursa
el 18 de Ag. de 2017
E.g.,
z = cell2mat(cellfun(@(x,y)repmat(x,1,y),num2cell(x),num2cell(y),'Uni',false));
But this just hides the loops in the background.
0 comentarios
Más respuestas (3)
Steven Lord
el 18 de Ag. de 2017
If you're using release R2015a or later, use repelem.
x = [3 6 7 10];
y = [2 2 2 4];
z = repelem(x, y)
0 comentarios
Jan
el 18 de Ag. de 2017
x = [3 6 7 10]
y = [2 2 2 4]
z = repelem(x, y);
Z = RunLength(x, y);
0 comentarios
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!