Skip to main content
v2026.11,986 entries · CC-BY 4.0

Projectile Motion in MATLAB: ode45 Trajectory with Drag

Step-by-step ode45 script for projectile motion in MATLAB, with drag models and events that return range, peak height and flight time.

Written and maintained by CASRAI Editorial Board

Published

On this page

To simulate projectile motion in MATLAB, write the motion as a first-order system with the state vector y = [x; y; vx; vy], pass it to ode45 as an anonymous function, and use an event function to stop the integration when the projectile returns to the ground. The call [t,y,te,ye,ie] = ode45(dydt,tspan,y0,options) then returns the whole trajectory plus the exact time and position of landing. The approach comes from MathWorks’ own air-resistance example, and this guide extends it into one script that handles no drag, linear drag and quadratic drag, and reads range and peak height straight from event outputs.

What it is used for in research

Projectile trajectories are a standard test problem for numerical integration and for modelling anything that is launched and then subject to gravity and drag: ballistics and sports biomechanics, sensor-platform drop tests, particle or droplet paths, and teaching labs on numerical methods. The motion has a closed-form solution only when air resistance is ignored. Once drag is added, the equations are normally integrated numerically, which is why an ODE solver is the usual tool.

Per MathWorks, with no air resistance the trajectory is a parabola. That fact is useful as a validation target: a simulation with the drag coefficient set to zero should reproduce the parabola, and any drag model you add should bend the path below it. For the general mechanics of the solver (tolerances, step control, output options) see the companion guide on ode45 in MATLAB; this page concentrates on the projectile model and its events.

Install or access (official source only)

ode45 is a core MATLAB function documented in the base MATLAB reference, so no additional toolbox is named on its documentation page. MathWorks states that MATLAB Online “runs directly in your browser without requiring any downloads, installations, or setup”, and that some add-ons may require a license; the desktop product is obtained from mathworks.com. If you do not have MATLAB at all, the free alternatives section below shows the same model in GNU Octave and in Python with SciPy.

Step-by-step: simulate a projectile with drag

All commands below follow the MathWorks documentation pages listed under Sources. Parameter values (g = 9.81, initial speed 300, μ = 0.02) are those used in the MathWorks example; change them for your own problem.

1. Define the state and the equations of motion

MathWorks uses the state vector y = [x; y; vx; vy], so the derivative function returns [vx; vy; ax; ay]. Three variants are given in the data table at the end of this page. The no-drag version is:

g = 9.81;
dydt = @(t,y) [y(3); y(4); 0; -g];

Linear (Stokes-type) drag, where deceleration is proportional to velocity, replaces the last two components with -mu*y(3) and -g-mu*y(4). Quadratic (Newton-type) drag, proportional to the square of speed, uses -mu*y(3)*sqrt(y(3)^2+y(4)^2) and -g-mu*y(4)*sqrt(y(3)^2+y(4)^2).

2. Set the initial conditions and time span

vInitial = 300;  theta = 45;  mu = 0.02;
yInitial = [0; 0; vInitial*cosd(theta); vInitial*sind(theta)];
tInitial = 0;
tFinal   = 2*vInitial*sind(theta)/g + 1;

The final time is the no-drag flight time plus one second. With drag the projectile lands earlier than that, so the span is long enough for the landing event to fire. cosd and sind take degrees.

3. Write an event function for apex and ground impact

An event function has the form [value,isterminal,direction] = myEventsFcn(t,y). MathWorks defines an event as occurring when value(i) equals zero; isterminal(i) = 1 stops the integration and 0 lets it continue; direction of 0 detects all zero crossings, +1 only increasing and -1 only decreasing ones. One function can return several events as vectors:

function [value,isterminal,direction] = projectileEvents(t,y)
    value      = [y(4); y(2)];   % 1: vertical velocity = 0 (apex), 2: height = 0 (ground)
    isterminal = [0; 1];         % keep going after apex, stop at ground
    direction  = [0; -1];        % ground event: only when height is decreasing
end

Using direction -1 for the ground event is an editorial choice that follows the pattern in MathWorks’ bouncing-ball example, which also uses direction = -1 with isterminal = 1: it prevents the starting position y = 0 from being read as a landing. Local functions like this go at the end of a script file, or in their own file.

4. Call ode45 with the Events option

options = odeset('Events',@projectileEvents);
[t,yout,te,ye,ie] = ode45(dydt,[tInitial tFinal],yInitial,options);

5. Extract range and peak height, then plot

range     = ye(ie==2,1);    % x at ground impact
maxHeight = ye(ie==1,2);    % y at apex
flightTime = te(ie==2);
plot(yout(:,1),yout(:,2),LineWidth=2)
xlabel('x'), ylabel('y'), axis tight

To compare against the drag-free parabola, MathWorks builds a reference curve from the simulated range and height: X = maxRange*(0:0.05:1); Y = 4*maxHeight*X.*(maxRange-X)/maxRange^2; and plots it beside the trajectory with a legend. Run the script once per drag model (or loop over launch angles, as the MathWorks example does for 15 to 75 degrees) and overlay the results.

Output and how to read it

The outputs have fixed meanings in the ode45 reference: t holds the evaluation points as a column vector, yout has one row per time point and one column per state component, te is the time of each event, ye the solution at each event, and ie the index of the event function that triggered. In this script yout(:,1) is horizontal position and yout(:,2) height, so plot(yout(:,1),yout(:,2)) draws the path in the x-y plane, not height against time.

Because the ground event is terminal, the last row of yout is the landing point and the last value of te is the flight time. The apex event is non-terminal, so it is logged and integration continues; ie tells you which row of te and ye belongs to which event.

Sanity check against the closed form

This check is editorial physics, not from the MathWorks page. With μ = 0, flat ground and the example values (300, 45 degrees, g = 9.81), the standard formulas give a range of v²sin(2θ)/g ≈ 9,174, a peak height of v²sin²θ/(2g) ≈ 2,294 and a flight time of 2v·sinθ/g ≈ 43.2 (units follow your inputs). If your event outputs differ by more than the solver tolerance, check the signs in dydt and the angle units before suspecting the solver.

Troubleshooting

  • The path never lands (no ground event). tFinal is too short or the event is filtered out. Lengthen the span, and confirm direction is 0 or -1 for a descending crossing.
  • Integration stops immediately. A terminal event with direction = 0 on the height will fire at t = 0 because height starts at zero. Use direction = -1 as above.
  • “Not enough input arguments” or errors in the derivative function. ode45 calls odefun(t,y). If your model needs parameters such as g or μ, capture them in an anonymous function (as dydt does here) rather than adding extra arguments. This is standard MATLAB behaviour, noted here as editorial guidance.
  • Wrong-looking trajectory. Degrees versus radians (cosd/sind versus cos/sin) and a swapped state order are the usual causes; keep the order [x; y; vx; vy] consistent between yInitial, dydt and the events.
  • Stiff behaviour. MathWorks calls ode45 “the first solver you should try for most problems” and notes that stiff problems may suit other solvers. Ordinary projectile models with moderate drag are not typically in that category. See solving equations in MATLAB for other solver families.

Free alternatives

The same event-driven approach exists in free tools. Octave’s ode45 supports the Events option with the same function form; SciPy uses a function with attributes instead.

Tool Solver call How events are declared Source
MATLAB ode45(odefun,tspan,y0,options) odeset('Events',@fcn); fcn returns [value,isterminal,direction]; extra outputs te, ye, ie MathWorks ode45 and event-location pages
GNU Octave ode45 (MATLAB-compatible) Events option; function form [value,isterminal,direction] = my_events_f(t,y); extra outputs te, ye, ie Octave manual, MATLAB-compatible solvers
Python / SciPy solve_ivp(fun,t_span,y0,method='RK45',events=...) Event function with attributes terminal (default False) and direction (0 for either, positive for negative-to-positive crossings only) SciPy solve_ivp reference

SciPy’s default method, RK45, is described as an explicit Runge-Kutta method of order 5(4), the same family as MATLAB’s ode45. For related numerical tasks see integrating in MATLAB, linspace in MATLAB for building time or angle grids, and 3D plotting in MATLAB if you extend the model to three dimensions. R users can look at the deSolve package guide.

FAQ

Which MATLAB function simulates projectile motion with air resistance?

ode45 with a derivative function for the state [x; y; vx; vy] and an Events option to stop at ground impact, as in the MathWorks air-resistance example.

How do I stop the simulation when the projectile hits the ground?

Return value = y(2), isterminal = 1 and direction = -1 from an event function and pass it with odeset('Events',...). Integration stops when height crosses zero while decreasing.

How do I get the maximum height?

Add an event on vertical velocity, value = y(4) with isterminal = 0, then read the height from the matching row of ye, selected with ie.

Do I need a toolbox?

The ode45 documentation page sits in base MATLAB; no toolbox is named for it there.

Can I do this without MATLAB?

Yes. GNU Octave’s ode45 accepts the same Events function, and SciPy’s solve_ivp offers events with terminal and direction attributes.

Sources

  • MathWorks, “Compare Air Resistance Models for Projectile Motion” (mathworks.com/help/matlab/data_analysis/compare-air-resistance-models-for-projectile-motion.html), read 2026-11-12.
  • MathWorks, “ode45” (mathworks.com/help/matlab/ref/ode45.html), read 2026-11-12.
  • MathWorks, “ODE Event Location” (mathworks.com/help/matlab/math/ode-event-location.html), read 2026-11-12.
  • MathWorks, “MATLAB Online” (mathworks.com/products/matlab-online.html), read 2026-11-12.
  • SciPy, “scipy.integrate.solve_ivp” (docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_ivp.html), read 2026-11-12.
  • GNU Octave manual, “Matlab-compatible solvers” (docs.octave.org/latest/Matlab_002dcompatible-solvers.html), read 2026-11-12.

Data: Projectile equations of motion for three air-resistance models in MATLAB ode45 state form

Compares the derivative terms for the state vector [x; y; vx; vy] under no drag, drag proportional to velocity and drag proportional to the square of speed, compiled from the MathWorks projectile air-resistance example.

Period covered: 2026.

Projectile equations of motion for three air-resistance models in MATLAB ode45 state form
Drag modelDrag lawdvx/dt (MATLAB)dvy/dt (MATLAB)
No air resistancenone0-g
Linear (Stokes-type)proportional to velocity-mu*y(3)-g-mu*y(4)
Quadratic (Newton-type)proportional to speed squared-mu*y(3)*sqrt(y(3)^2+y(4)^2)-g-mu*y(4)*sqrt(y(3)^2+y(4)^2)

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about Projectile Motion in MATLAB: ode45 Trajectory with Drag

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →