% Matlab diary from cs110a, Mar 2 2005. % % This is what I typed in class. % % Type it into Matlab yourself to % reproduce the output I showed. edit f % this is the falling-object f from last time ode45(@f, [0 2], [1 ; 0]); opts = odeset('events', @stopper); opts edit stopper type stopper function [gstop, isterminal, direction] = stopper(t,y) % STOPPER : stopping criterion function for falling body % % gstop = 0 is the event this handler recognizes % return gstop = height above ground, so ode will stop when it hits ground gstop = y(1); % the "event" happens when gstop = 0 isterminal = 1; % the "event" ends the execution of ode45 direction = [] ; % don't care which direction gstop hits zero from [T, Y, tfinal] = ode45(@f, [0 2], [1 ; 0], opts); clf tfinal tfinal = 1.6575 size(Y) plot(T,Y(:,1)) edit stopper type stopper function [gstop, isterminal, direction] = stopper(t,y) % STOPPER : stopping criterion function for falling body % % gstop = 0 is the event this handler recognizes % return gstop = height above ground, so ode will stop when it hits ground gstop = y(1)-.5; % the "event" happens when gstop = 0 isterminal = 1; % the "event" ends the execution of ode45 direction = [] ; % don't care which direction gstop hits zero from [T, Y, tfinal] = ode45(@f, [0 2], [1 ; 0], opts); tfinal plot(T,Y(:,1)) ode45(@f, [0 2], [1 ; 0]); edit f type f function ydot = f(t,y) % F : function ydot = f(t,y) for ODE solution % % t: scalar time % y: vector, y = y(t), unknown function % % ydot: vector of dy / dt ydot = y / 2; ode45(@f, [0 10], 1); hold on type ode1 function ode1(F, tspan, y0, h) % ODE1 : demo version of simple Euler method % ode1(F, tspan, y0, h) uses step size h and plots 1D results t0 = tspan(1); tfinal = tspan(2); t = t0; y = y0; plot(t,y,'r.'); hold on while t <= tfinal y = y + h*feval(F,t,y); t = t + h; plot(t,y,'r.') end; h = 1 ode1 ( @f, [0 10], 1, h); h = .5 ode1 ( @f, [0 10], 1, h); h = .1 ode1 ( @f, [0 10], 1, h); h = .001; ode1 ( @f, [0 10], 1, h);