MATLAB Answers

ODE event: Is there a counter ?

4 views (last 30 days)
Hi, Is there a way to terminate after an event occurs a certain number of times? I am thinking of using a counter in the ODE event function. But I am not sure how to pass it as an argument to the event function.
Thank you,

More Answers (1)

Kiran Felix Robert
Kiran Felix Robert on 22 Mar 2021
Hi Siddhartha,
You don’t have to pass the counter as an argument to the event function, you can define the count variable as a global variable (persistent) and increment/decrement it, while not terminating the integration, until the control arrives at a count to terminate the integration.
Refer the answer here (syntax example) and ODE Event Location documentation.
The following snippet can be used as an example, for 10 events.
function [value,isterminal,direction] = Eventsfcn(t,y)
persistent count;
if isempty(count)
count = 10;
if count > 1
% Your code here
count = count - 1;
isterminal = 0; % Do not stop the integration
% Your Code here
isterminal = 1; % Stop the integration
Siddhartha Harsha Ommi
Siddhartha Harsha Ommi on 28 Mar 2021
To update, I have tried the following naive approach which seemed to work for simpler cases that involve less significant digits. Also, I am not sure how to adapt this to also look at the particular direction from which the event occurs. Probably need to take inspiration from the source code.
function [value,isterminal,direction] = Eventsfcn(t,y)
value = [(y(1)-0.5); y(2); y(3)]; % for solution=0.5; slope = 0.0; curvature = 0.0;
direction = [0; 0; 0] % such events could occur from either directions
persistent cnt;
if isempty(cnt)
cnt = 0;
if y(2)==0 % vanishing curvature. Could be other criteria aswell.
cnt = cnt + 1;
if cnt > 9 % if vanishes 10 times change the terminal
isterminal = [0; 0; 1];
isterminal = [0; 0; 0]; % default terminal
However, in my case I am working with a higher number of significant digits and this seemed to be working but only errattically.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!