Variable size changes on every iteration

Hi,
What is an efficient way of doing the following task.
departure_time(1) = 250;
file_arrival(1) = 0.0;
for i = 2:30
departure_time(i) = arrival_time(i)+transmission_time(i)+departure_time(i-1);
end
This code is working fine for me but the matlab script editor show the message that "the variable departure_time changes size on every loop iteration. I am sure that there will be another way of achieving the same task, right?
Thank you so much.

 Respuesta aceptada

José-Luis
José-Luis el 5 de Jun. de 2014
Editada: José-Luis el 5 de Jun. de 2014
Pre-allocate. Before departure(1) = 250, place:
departure_time = NaN .* ones(30,1);

4 comentarios

Aftab Ahmed Khan
Aftab Ahmed Khan el 5 de Jun. de 2014
Editada: Aftab Ahmed Khan el 5 de Jun. de 2014
Hi, it works fine Thank you so much. Can you explain it to me that one line of yours? Plus i have few other lines as well with the same kind of situation, i think i can replace them as well, right ?
José-Luis
José-Luis el 5 de Jun. de 2014
The thing with Matlab is if that you don't tell it what size a variable will be, it will increase its size as long as you keep appending stuff to it, as you do in that loop.
That is very inefficient computationally: since the elements of a matrix are placed contiguously in memory, said memory needs to be reallocated when you increase the size of your array.
A way to prevent that is to tell Matlab beforehand the size the final array will have: pre-allocation.
Please accept an answer if it helped you.
Aftab Ahmed Khan
Aftab Ahmed Khan el 5 de Jun. de 2014
Thanks for the explanation, Accepted.
Cheers.
José-Luis
José-Luis el 5 de Jun. de 2014
My pleasure, thank you.

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 5 de Jun. de 2014

Comentada:

el 5 de Jun. de 2014

Community Treasure Hunt

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

Start Hunting!

Translated by