It looks like you're using global
variables incorrectly (f
needs to be declared global
in your main function as well), but you shouldn't be using globals to begin with. You should rarely, if ever, use globals. You should also specify your integration function, odefun
, as an anonymous function rather than a string in modern Matlab. Here is how you can modify your code to fix these issues:
...
f = ...
[x,y] = ode45(@(x,y)odefun(x,y,f),xspan,y0);
And your integration function, which can be a sub-function or in a separate file, just needs to take an extra argument for the parameter f
:
function dy=odefun(x,y,f)
dy(1) = y(2);
dy(2) = -f.*y(2);
dy = dy(:);
The methods should also be faster than using strings and globals. The code @(x,y)odefun(x,y,f)
creates an anonymous function of x
and y
(ode45
expects a function that takes exactly two inputs) that captures the value of f
from the current scope. This is also referred to as a closure in computer science. You can equivalently create a function handle and pass that in:
...
f = ...
fun = @(x,y)odefun(x,y,f)
[x,y] = ode45(fun,xspan,y0);
See also this article on parametrizing functions from The MathWorks for more information on this general technique.