MATLAB: Stopping plot when y is less than zero

maskingMATLABplotplottingprojectile

I have this code for projectile motion, but I need to stop the plot when y<0. How could I do this?
global m cd A rho g theta v0 x0 y0
m= [0.145 0.42 0.43]; % mass of projectile [kg]
cd= [0.3 0.5 0.25]; % drag coefficients
A= [0.00426 0.02318 0.038]; % cross sectional area of projectile [m^2]
V= [0.0002194 0.00462115 0.00573547]; % volume of projectile
rho= [m(1)/V(1) m(2)/V(2) m(3)/V(3)]; % density
g= 9.8; % gravity [m/s^2]
theta= 30*pi/180; % initial launch angle [rad]
x0= [0 0 0]; % initial horizontal position
y0= [1.8288 1.8288 0]; % initial vertical position
v0= [18 18 22]; % initial velocity (m/s)
%set projectile, 1=baseball, 2=football, 3=soccer ball
proj=3;
m= m(proj);
cd= cd(proj);
A= A(proj);
rho= rho(proj);
x0= x0(proj);
y0= y0(proj);
v0= v0(proj);
% call function
[t y]= ode45(@my_fun,[0 2],[x0 y0 v0 theta]);
% Verification
max_y= max(y(:,2)); % maximum vertical height of projectile [m]
% plotting results
figure(1)
plot(t,y(:,1))
grid on
xlabel('time [s]')
ylabel('horizontal position [m]')
title('plot of horizontal location vs time')
figure(2)
plot(t,y(:,2))
grid on
xlabel('time [s]')
ylabel('vertical position [m]')
title('plot of vertical location vs time')
figure(3)
plot(y(:,1),y(:,2))
grid on
xlabel('horizontal position [m]')
ylabel('vertical position [m]')
title('plot of vertical location vs horizontal position')
end
%% Function
function dy=my_fun(t,y) % y is a matrix containing [x y v theta]
global m cd A rho g theta x0 y0 v0
dy=zeros(4,1);
dy(1)= y(2); %dx/dt
dy(2)= y(3); %dy/dt
dy(3)= -(cd*A*rho)/(2*m)*sqrt((dy(1))^2+(dy(2))^2)*dy(1); % d2x/dt2
dy(4)= -g-(cd*A*rho)/(2*m)*sqrt((dy(1))^2+(dy(2))^2)*dy(2); % d2y/dt2
end

Best Answer

Define the following function in your code
function [event,isterminal,direction] = odeEvent(t,y)
event = y(2); % observe y(2)=0
isterminal = 1; % stop on observing y(2)=0
direction = -1; % observe that y(2) is decreasing before the event y(2)=0
end
and then call ode45 like this
odeOpt = odeset('Events', @odeEvent);
[t y]= ode45(@my_fun,[0 2],[x0 y0 v0 theta], odeOpt);