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

1 view (last 30 days)
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.

Answers (1)

Sulaymon Eshkabilov
Sulaymon Eshkabilov on 19 Aug 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.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!