Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)]';
like image 387
Legend Avatar asked Feb 13 '10 02:02

Legend


1 Answers

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);
like image 73
catchmeifyoutry Avatar answered Sep 19 '22 21:09

catchmeifyoutry