function  eventsdemo
%Canonball lands on ground

%This is how to end integration at an 'EVENT'
%like some variable reaching some value.


options=odeset('events',@f2);



tspan = linspace(0,100,1001);
v0=100;
[t,z,tev, zev, i] =  ode45(@f,tspan,[0 0 v0 v0],options);



plot( z(:,1), z(:,2) ); axis('equal');
end

function zdot = f(t,z);
r = z(1:2);
v = z(3:4); s = norm(v);  % speed
Fric = - .1* s.*v
rdot = v;
vdot = Fric+ [ 0  -10]'; % note the quadratic drag
zdot = [rdot;vdot]; % 
end



function [value,done,dir] = f2(t,z)
%Integration stops (done = 1) when value = 0.
%In this case when the cannon ball hits
%the ground (y=0)  from above (that's dir = -1).
 value = z(2) ;  done = 1;  dir= -1; 
end


