MATLAB: How do I pass a parameter to a function?

Legend picture Legend · Feb 13, 2010 · Viewed 20.2k times · Source

I have the following function:

function ypdiff = ypdiff(t,y)
    a = 0.01;
    b = 0.1;
    ypdiff(1) = -a*y(1)*y(2);
    ypdiff(2) = b*y(1)*y(2)-b*y(2);
    ypdiff(3) = b*y(2);
    ypdiff = [ypdiff(1) ypdiff(2) ypdiff(3)]';

If I want to solve this, I would call the ode45 function as follows:

[t y] = ode45(@ypdiff, [to tf], yo);

But if I want to pass a parameter to this function, how would I use the ode45 function? Specifically, I am trying for the following formulation:

function ypdiff = ypdiff(t,y,u)
    a = 0.01;
    b = 0.1;
    ypdiff(1) = -a*u*y(1)*y(2);
    ypdiff(2) = b*u*y(1)*y(2)-b*y(2);
    ypdiff(3) = b*u*y(2);
    ypdiff = [ypdiff(1) ypdiff(2) ypdiff(3)]';

Answer

catchmeifyoutry picture catchmeifyoutry · Feb 13, 2010

You can use an anonymous function in matlab (similar to lambda functions in other languages):

u = 1.2;
[t y] = ode45(@(t, y) ypdiff(t, y, u), [to tf], yo);