function odemwe % Output step size dt = 1.00000001e-1; dt = 1.0e-1; x0 = [1; 0]; tStart = 0; tStop = 2; tout = (tStart:dt:tStart+dt*(2+fix((tStop-tStart)/dt)))'; opt = odeset('events', @ode_events, 'abstol', 1e-6, 'reltol', 1e-6); [t, x, te, xe, ie] = ode15s (@f, tout, x0, opt); fprintf ("index of triggered event / time of event: [%d, %f]\n", ie, te); figure; subplot (2, 1, 1); plot (t, x(:,1), '*'); set (gca, 'xlim', [0 1.5], 'ylim', [0 1]); title ("Position over Time"); xlabel ("t"); ylabel ("x"); grid on; subplot (2, 1, 2); plot (t, x(:,2), '*'); set (gca, 'xlim', [0 1.5], 'ylim', [-2 0]); title ("Velocity over time"); xlabel ("t"); ylabel ("x'"); grid on; % ODE function dxdt = f(t, x) dxdt = [x(2); -x(1)]; end % Event handling callback function [value, isterminal, direction] = ode_events(t, x, dt) % Expression to be evaluated value = t - 1; % Halt integration isterminal = 1; % Zero can be approached from either direction direction = 0; end end