I am trying to use Events option in ode45, please help!

7 views (last 30 days)
Hello, I am trying to solve an ODE function using ode45. I need to find the point at which the value is zero (y=0). This is my code:
-----------main code-----------------
% Setting the global variables
global r lambda mu sig D
% Define values
r = 0.06;
lambda = 0.01;
mu = 0.18;
sig = 0.09;
D = 0.18;
% Define boundary points
g01 = 0;
g02 = 100;
% Define tspan
w0 = 0.001;
wf = 10;
gf = [g01 g02];
gwspan = [w0 wf]; % reverse the order of tspan for "Final vlaue problem"
options = odeset('Events',@yzero);
[wg,g] = ode45('dg',gwspan,gf,options);
--------------ODE------------------------
function gdot = dg(w,g)
% Define parameters values
global r lambda mu sig;
gdot = zeros(2,1);
gdot(1) = g(2);
gdot(2) = (2/sig^2)*(r*g(1)-((r-lambda)*w+mu)*g(2));
end
----------------Event function ----------------------------
function [value,isterminal,direction] = yzero(~,y)
% Locate the time when the value is zero
% increasing direction and don't stop integration.
value = y(1); % detect value at zero
isterminal = 0; % don't stop the integration
direction = 1; % positive direction only
end
When I run it, I get the following error messeges:
SWITCH expression must be a scalar or string constant.
Error in odeevents (line 31) switch lower(eventFcn)
Error in ode45 (line 147) [haveEventFcn,eventFcn,eventArgs,valt,teout,yeout,ieout] = ...
Error in main_g_GBM (line 29) [wg,g] = ode45('dg_GBM',gwspan,gf,options);
could you please tell me what is wrong with my code? Any help would be really appreciated.

Accepted Answer

Walter Roberson
Walter Roberson on 30 Nov 2015
You used the function name string for your ode function but you used the function handle for you events. The ode routines expect you to be consistent.
Fix:
[wg, g, te] = ode45(@dg, gwspan, gf, options);
Note the change from 'dg' to @dg
The additional te argument is the time of the event.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!