How to write an event function to stop at second or third x axis crossing.
33 views (last 30 days)
Show older comments
I need my function to stop at a specific x crossing, but it has several and the one I need is the third that occurs over time. I tried writing a loop that made the stopping of the function contingent on multiple values (y component = 0 and y velocity being positive). But it's not stopping the function at all.
function [value, isterminal, direction] = xcross(t, state_xyz, mu)
v1 = state_xyz(2);
v2 = state_xyz(5);
value = v1;
if v1 == 0 && v2 > 0
isterminal = 1;
else
isterminal = 0;
end
direction = 0;
end
0 Comments
Answers (2)
Sameer
on 15 Nov 2024 at 9:23
Hi @Madeleine
To stop at the third x-axis crossing, you need to count the number of crossings and stop when the count reaches three. You can achieve this by using a "persistent" variable to keep track of the number of crossings that have occurred.
Here's how you can modify your function:
function [value, isterminal, direction] = xcross(t, state_xyz, mu)
persistent crossing_count;
if isempty(crossing_count)
crossing_count = 0;
end
v1 = state_xyz(2);
v2 = state_xyz(5);
value = v1;
direction = 0;
% Check if it's a crossing
if v1 == 0 && v2 > 0
crossing_count = crossing_count + 1;
end
% Stop at the third crossing
if crossing_count == 3
isterminal = 1;
else
isterminal = 0;
end
end
Hope this helps!
0 Comments
Torsten
on 15 Nov 2024 at 11:01
Edited: Torsten
on 15 Nov 2024 at 11:07
I'd make the solver stop at each x-crossing. After it returns control to the calling program, add 1 to the number of crossings and restart the solver if the third crossing has not yet been reached or stop the integration if the number of crossings has reached three.
Take a look at the ballode example on how to save the solution so far and restart the solver in a loop:
If you manage to modify the example such that the solver stops at the third time the ball hit the ground, you can easily use the code in your application.
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!