Event function not halting integration

15 views (last 30 days)
My Event function looks like this. It is meant to stop the integration of my ODE45 solver function when Xconcentration <= 20. It does this for the first couple of instances, but then when Xconcentration drops below 20 again, it does not halt the integration, even as Xconcentration gradually decreases towards 0. Why would it work for the first ~40 times but not the rest? Any help would be great.
function [value,isterminal,direction] = TransferEvent(t, Xconcentration)
VAL = 1;
for bb = 33:11:121
if Xconcentration(bb) <= 20 || Xconcentration(bb) >= 30
VAL = 0;
end
end
value = VAL; % The value that we want to be zero
isterminal = 1; % Halt integration
direction = 0; % The zero can be approached from either direction
end

Accepted Answer

Steven Lord
Steven Lord on 22 Jun 2021
Rather than making your event function return either true or false (or 1 or 0) that indicates whether the event function thinks an event has occurred, have it return a continuous value and let the ODE solver detect where that reaches / passes through 0.
For instance, in the documentation example the first events function appleEventsFcn does not return y(1) == 0 or y(1) < 0 which would be either false (0) or true (1). Instead it returns y(1). The ODE solver will evaluate the events function and determine the time when the event solver's first output has a zero crossing in the specified direction.
The other two events functions, bounceEvents and orbitEvents, behave the same way by returning a continuous value and allowing the solver to interpret the outputs.
  3 Comments
Steven Lord
Steven Lord on 22 Jun 2021
So you have nine different potential events? The orbitEvents function detects two different potential events since the value, isterminal, and direction variables it returns are each 2-by-1 vectors. You'd do the same but return 9-by-1 vectors instead.
Sebastian Schultz
Sebastian Schultz on 22 Jun 2021
I have lower and upper limits that I need it to stop at, so 18 in total. But following your advice I have gotten my funtion to work as intended! Thank you very much for the help.

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!