How to stop ode45 when value reach certain value other-than zero

I need to stop the ode when y(2) is 0.2 and here is the function I used for the solver but It doesn't work. Any thing wrong with it ?
function [val, terminate, dir]= stopevents(t,y)
val=(y(2)==0.2)-0.5;
terminate=1;
dir=0;
end

回答 (2 件)

Jan
Jan 2018 年 4 月 26 日
編集済み: Jan 2018 年 4 月 26 日

1 投票

An event occurs when value(i) is equal to zero.
function [value, terminate, direction] = stopevents(t, y)
value = y(2) - 0.2;
terminate = 1;
direction = 0;
end
The event function must be smooth. It is extremely unlikely, that the integration meets the point y(2)==0.2 exactly. Therefore your event function does not trigger. In addtion:
val = (y(2)==0.2)-0.5;
replies -0.5 or 0.5, but never 0, which would trigger the event.
By the way: Avoid using "dir" as name of a variable, because this shadows an important built-in function.

5 件のコメント

Dereje
Dereje 2018 年 4 月 26 日
Thanks for the comment. Like you said it never reached 0.2. But, is there any way/means that might trigger stopping events other than this ?
Bjorn Gustavsson
Bjorn Gustavsson 2018 年 4 月 26 日
Just adjust the events function from ballode.m to return ZERO for the value you want to flag an event. Something like this:
function [value,isterminal,direction] = events(t,y)
% Locate the time when height passes through zero in a decreasing direction
% and stop integration.
value = y(1)-your_val; % detect height = 0
isterminal = 1; % stop the integration
direction = -1; % negative direction
Then it should trigger the event, and your ODE-function will know how to refine the solution around that.
HTH
Jan
Jan 2018 年 4 月 26 日
@Dereje: I do not understand your comment. It is unlikely the the integration hits 0.2 exactly, because it proceeds in steps. Uing value = y(2) - 0.2 let the integrator locate the time, where y(2) is exactly 0.2, because it detects that this function changes its sign. But with value=(y(2)==0.2)-0.5 this detection cannot work.
What do you mean by "other than this"? I've posted a working solution.
Dereje
Dereje 2018 年 4 月 26 日
@Jan y(2)-0.2 is not working that is why I asked you but it works for zero.May be something is wrong with my code. @Bjorn Gustavsson Thanks for the detailed clarification.
Bjorn Gustavsson
Bjorn Gustavsson 2018 年 4 月 27 日
@jan: I guess what was meant with y(2) is y(t) for t=2, and not the second component of y

サインインしてコメントする。

Bjorn Gustavsson
Bjorn Gustavsson 2018 年 4 月 26 日

0 投票

You should be able to use the "events handling", look at the code for ballode.m for an example on how to handle it.
HTH

1 件のコメント

Dereje
Dereje 2018 年 4 月 26 日
But in that case the stopping condition is when y is 0.

サインインしてコメントする。

カテゴリ

質問済み:

2018 年 4 月 26 日

コメント済み:

2018 年 4 月 27 日

Community Treasure Hunt

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

Start Hunting!

Translated by