Skip to content
MATLAB

ODE Solvers

Solve ordinary differential equations with ode45.

By EZ4Code Team
odesolvernumerical

Code

% dy/dt = f(t, y)
% System: dy1/dt = y2, dy2/dt = -y1 (harmonic oscillator)

odeFun = @(t, y) [y(2); -y(1)];

[t, Y] = ode45(odeFun, [0 10], [1; 0]);
% t: time points, Y: solution at each time

plot(t, Y(:,1), 'b-', t, Y(:,2), 'r--');
xlabel('t'); legend('position', 'velocity');

% Stiff ODE: use ode15s instead
% [t, Y] = ode15s(odeFun, [0 10], [1; 0]);

% With parameters:
odeFun = @(t, y, k) [y(2); -k*y(1)];
[t, Y] = ode45(@(t,y) odeFun(t, y, 2.0), [0 10], [1; 0]);

Explanation

ode45 is the go-to ODE solver (Runge-Kutta 4(5) with adaptive step). For stiff systems, use ode15s. Pass parameters via anonymous function closure. The solver returns time points t and solution Y — each column of Y corresponds to a state variable.

More MATLAB Snippets