How do I preallocate my variables for speed when creating an SIR model?

1 visualización (últimos 30 días)
Hello. I am currently trying to graph an SIR model using matlab. I have a for loop in my code. My graph never seems to look right and I'm wondering if preallocating for speed might help. (Matlab also suggested this to me.)
My code is as follows:
for i=1:H
% Update time
t(i+1)=t(i)+h;
% Update S, I & R
k1S = fS(t(i) , S(i) , I(i) );
k1I = fI(t(i) , S(i) , I(i) );
k1R = fR(t(i) , I(i) );
k2S = fS(t(i)+h/2, S(i)+h/2*k1S, I(i)+h/2*k1I);
k2I = fI(t(i)+h/2, S(i)+h/2*k1S, I(i)+h/2*k1I);
k2R = fR(t(i)+h/2 , I(i)+h/2*k1I);
k3S = fS(t(i)+h/2, S(i)+h/2*k2S, I(i)+h/2*k2I);
k3I = fI(t(i)+h/2, S(i)+h/2*k2S, I(i)+h/2*k2I);
k3R = fR(t(i)+h/2 , I(i)+h/2*k2I);
k4S = fS(t(i)+h , S(i)+h *k3S, I(i)+h *k3I);
k4I = fI(t(i)+h , S(i)+h *k3S, I(i)+h *k3I);
k4R = fR(t(i)+h , I(i)+h *k3I);
S(i+1) = S(i) + h/6*(k1S + 2*k2S + 2*k3S + k4S);
I(i+1) = I(i) + h/6*(k1I + 2*k2I + 2*k3I + k4I);
R(i+1) = R(i) + h/6*(k1R + 2*k2R + 2*k3R + k4R);
end
I could really use some help in figuring out how to get my model to work. Thanks.

Respuestas (1)

Sulaymon Eshkabilov
Sulaymon Eshkabilov el 19 de Ag. de 2019
Memory allocation does not correct your code's errors. It helps to speed up the process of calculation and simulation. Your udpate of time: t(i+1) = t(i)+h does not appear to be appropriately placed within your loop since you are using t(i)+h/2 and t(i)+h later.

Categorías

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

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by