How can make my Loop more efficient?

I have this Loop
m=0.05;
for
i=1:1000;
r= poissrnd(m);
t(1,i)= r;
end
t
there is an orange tag to right of this line "" t(1,i)=[r]; "" says ( the variable appears to change size on every loop iteration. consider preallocating for speed)
What should I do to make my loop more efficient?

 Respuesta aceptada

Cam Salzberger
Cam Salzberger el 20 de Sept. de 2017
Editada: Cam Salzberger el 20 de Sept. de 2017
If you preallocate the variable before the loop, the variable will not have to grow in size within the loop. Growing in size is an issue because it forces MATLAB to allocate a different memory block for the variable, copy over the data, and then delete the old memory every time. You can preallocate with:
t = zeros(1, 1000);
Of course, you could eliminate the "for" loop and just generate the array of Poisson random numbers directly:
t = poissrnd(m, 1, 1000);
-Cam

3 comentarios

zeezo
zeezo el 20 de Sept. de 2017
Thank you Cam.
Do you mean I should write like this :
t = zeros(1, 1000);
m=0.05;
for
i=1:1000;
r= poissrnd(m);
t(1,i)= r;
end
t
Am I understanding right?
Thanks
Cam Salzberger
Cam Salzberger el 20 de Sept. de 2017
Yes, that would take care of the preallocation. Really consider generating all the numbers in one go though, and avoid the loop entirely.
zeezo
zeezo el 20 de Sept. de 2017
Thank you very much.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 20 de Sept. de 2017

Comentada:

el 20 de Sept. de 2017

Community Treasure Hunt

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

Start Hunting!

Translated by