Event function with multiple events

84 views (last 30 days)
I'm calling a events function as below for ode45:
option2 = odeset('Events', @comp);
[time, Y] = ode45(dYdt, tspan, y0, option2);
The function looks as follow:
function [position, isterminal, direction] = comp(t, Y)
x = Y(1); %x-coordinate
y = Y(2); %y-coordinate
xL = x*cos(Par.theta) + y*sin(Par.theta);
xL1 = Par.x1*cos(Par.theta); %[m]
xL2 = Par.x2*cos(Par.theta); %[m]
position = [xL1-xL; xL2-xL; Par.S-Y(end,1)];
isterminal = [0; 0; 1];
direction = [1; 1; -1];
I keep getting the error "Undefined variable "Par" or class "Par.theta"." When I substitute the variables with other variables not in a structure I then get the error "Not enough input arguments", but I've checked each variable is accounted for.
Anyone one with a suggestion on how to correctly call a structure variables' values in a function would be appreciated.
  1 Comment
Christo van Rensburg
Christo van Rensburg on 16 Sep 2019
So when I call the structure as such,
function [position, isterminal, direction] = comp(t, Y, Par)
it still gives the error of not enough input arguments. I cannot understand what input argument is missing?

Sign in to comment.

Accepted Answer

Steven Lord
Steven Lord on 16 Sep 2019
When you define your options structure with:
option2 = odeset('Events', @comp);
the ODE solver will call your Events function comp with two input arguments. Changing the definition of comp to accept a third input argument is one of the steps you need to follow to call your Events function comp with three inputs. The easiest way to complete the next step is to change your odeset call. Assuming Par is defined before you call odeset and does not change during the ODE solution process, specify your Events function as an anonymous function.
% Par is defined at this point
option2 = odeset('Events', @(t, y) comp(t, y, Par));
Ther are other techniques for passing additional parameters into one of the function (the ODE function, Events functions, etc.) that you pass into the ODE solvers. See this documentation page for more information.
Subhadeep Kumar
Subhadeep Kumar on 10 Dec 2019
@oski89 define Par as a global variable. Initialize Par in the main script. That will do the job unless you are using parallel computing for solving your problem. Global variable have its own demerits.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by