MATLAB Answers

0

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

Asked by Anika Ang on 19 Aug 2019 at 1:54
Latest activity Answered by Sulaymon Eshkabilov on 19 Aug 2019 at 2:09
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.

  0 Comments

Sign in to comment.

1 Answer

Answer by Sulaymon Eshkabilov on 19 Aug 2019 at 2:09

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.

  0 Comments

Sign in to comment.