How to write an event function to stop at second or third x axis crossing.
33 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Sameer
2024-11-15,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 个评论
Torsten
2024-11-15,11:01
编辑:Torsten
2024-11-15,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 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!