1

I have a function (for an SIR model), and then a script that solves this function and compares it to the data I am trying to fit this model to. Thus I am trying to run a for loop to change a parameter in the function in order to optimize the fit. I'm wondering how to change my the (r) and (a) parameters in a for loop without having to change them by hand:

function ydot=epidemic(t,y)
r=0.000001;
a=1/3;
ydot=zeros(3,1);
ydot(1)=-r*y(1)*y(2);
ydot(2)=r*y(1)*y(2)-a*y(2);
ydot(3)=a*y(2);
end

and

[t,y]=ode45('epidemic',[0:222], [70500,1,0])

Thanks

Ben Smith
  • 13
  • 2
  • 1
    Possible duplicate of [MATLAB: How do I pass a parameter to a function?](http://stackoverflow.com/questions/2256229/matlab-how-do-i-pass-a-parameter-to-a-function) or [this one](http://stackoverflow.com/questions/7680224/matlab-ode45-how-to-change-a-parameter-inside-it-while-calling-it). See also the [relevant documentation](http://www.mathworks.com/help/matlab/ref/ode45.html#bu3uhuk) and [this](http://www.mathworks.com/help/matlab/math/parameterizing-functions.html). – horchler Mar 21 '16 at 16:07

1 Answers1

2

You can use the following: you add the r and a parameter to your function

function ydot=epidemic(t,y,r,a)
    ydot=zeros(3,1);
    ydot(1)=-r*y(1)*y(2);
    ydot(2)=r*y(1)*y(2)-a*y(2);
    ydot(3)=a*y(2);
end

and then pass the function to ode45 like that

r = 0.000001 ;
a = 1/3 ;
[t,y]=ode45(@(t,y)epidemic(t,y,r,a),[0:222], [70500,1,0])

Basically, @(t,y)epidemic(t,y,r,a) defined a new function with arguments (t,y) and where r and a are using the values defined just above.

Then you can put all of that in a for loop.

Shawn
  • 593
  • 4
  • 12