How do I pass parameters to event functions for an ODE solver such as ODE45 within MATLAB?

38 views (last 30 days)
I want to pass a parameter to an event function in ODE45 so that I can have the solver stop when the solution decreases below 5 units instead of below 0.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 20 Dec 2011
If the event function is created as a nested function, you do not need to pass the additional parameters into the event function. An example of this can be seen in the attached file: "ballstepode_r14.m". This function is a variation of the MATLAB function called "ballode.m" supplied with MATLAB.
If the event function is not a nested function, you need to pass the additional parameters to the event function. To pass the additional parameters, say "P1" and "P2", first define the event function 'MyEventFunction' with the additional inputs as follows:
[VALUE, ISTERMINAL, DIRECTION] = MyEventFunction(T, Y, P1, P2)
The function associated with the EVENTS property in ODESET only takes 2 inputs (T,Y). To pass the additional parameters to the OPTIONS structure, define another function, say 'xoverFcn', which depends on the additional parameters "P1" and "P2" but only has 2 inputs to satisfy the requirements of the function associated to the EVENTS property. For example, define 'xoverFcn' as follows:
xoverFcn = @(T, Y) MyEventFunction(T, Y, P1, P2);
Then use 'xoverFcn' for the EVENTS property as follows:
options = odeset('Events',xoverFcn);
If you are using a version of MATLAB prior to MATLAB 7.0 (R14), you will need to pass the optional parameters "P1", "P2", etc., which you pass to the ODE45 function to be used in the system of ODEs to be solved, into event functions defined in the OPTIONS structure. For example, if you call the following:
[T, Y, TE, YE, IE] = ODE45(ODEFUN, TSPAN, Y0, OPTIONS, P1, P2)
and the EVENTS property of the OPTIONS structure is set to MyEventFunction, then ODE45 will call MyEventFunction using the following syntax:
[VALUE, ISTERMINAL, DIRECTION] = MyEventFunction(T, Y, P1, P2)
An example of this can be seen in the attached MATLAB file "ballstepode.m".

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!