concatenating vectors generated with loop

4 visualizaciones (últimos 30 días)
alpedhuez
alpedhuez el 27 de Mzo. de 2018
Comentada: Stephen23 el 2 de Abr. de 2018
I would like to run a for loop like
for i=1:N
output=[1 i]
output2 = [output2 output]
end
But in this example it seems that I need to define output2 at the beginning. Is there any compact way to write this operation?
  1 comentario
Stephen23
Stephen23 el 2 de Abr. de 2018
Expanding the array on each iteration will (in general) slow down your code. As David Goodmanson wrote, it is good practice preallocate the output array before the loop. Read this to know more:

Iniciar sesión para comentar.

Respuesta aceptada

David Goodmanson
David Goodmanson el 27 de Mzo. de 2018
Editada: David Goodmanson el 27 de Mzo. de 2018
Hi alpedhuez, define output2 by putting
output2 = [];
just before the do loop.
Unless you are using the intermediate results somehow, concatenation in this manner is not recommended. For N = 10000 or less it's all right in terms of execution time. But with execution time growing rapidly, eventually it makes more sense (and is better practice anyway) to define an array by output2 = ones(1,2*N) and then fill all the even entries with output2(2:2:2*N) = 1:N

Más respuestas (1)

David Fletcher
David Fletcher el 27 de Mzo. de 2018
Editada: David Fletcher el 27 de Mzo. de 2018
Not really more compact, but it does away with the loop
N=10
output=reshape([ones(1,N); 1:N],1,2*N)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by