Using Event function to solve ODEs

I am solving a set of n differential equations using ode15s. x is the n-dimensional vector.
sol = ode45(@this_model, [0,tmax], x, options);
I need to do this - whenever the value of any one of the values x(i) in the vector x falls below a threshold value th, I stop the solver, set the value of x(i) to zero and restart the solver again.
Thus,
options = odeset('NonNegative',1:n,'Events',@this_event);
and the event function is:
function [value,isterminal,direction] = this_event(~,x)
th = 1e-3;
value = min(x) > th;
isterminal = 1;
direction = 0;
end
However, this gives the error : Undefined function 'sign' for input arguments of type 'logical'.
Instead if I define my events function as:
function [value,isterminal,direction] = this_event(~,x)
th = 1e-3;
if min(x) < th
value = 0;
else
value = 1;
end
isterminal = 1;
direction = 0;
end
But when I do this, the solver does not stop even when the values of x(i) go below the threshold th.
Where am I wrong? Please help!

2 Comments

Why don't you simply set
value = x - th
?
Thank you for the reply, Torsten
That actually wont work. I actually debugged the problem. The following code works.
Actually, after one time the function is called, for all the remaining calls, 0 will be the overall minimum. So I have to put x(i)>0 along with the minimum condition.
function [value,isterminal,direction] = ext_thresh_event(~,x)
th = 1e-7;
n=length(x);
for i = 1:n
if x(i)>0 && x(i)<ext_thresh_value
value = zeros(n,1);
break;
else
value = ones(n,1);
end
end
isterminal = ones(n,1);
direction = zeros(n,1);
end

Sign in to comment.

Answers (0)

Products

Release

R2018a

Asked:

on 8 Mar 2019

Edited:

on 12 Mar 2019

Community Treasure Hunt

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

Start Hunting!