numericaloptimization

ODE45 — Solve an ODE

Solve a damped harmonic oscillator with ode45 — the workhorse of engineering coursework.

MATLAB's `ode45` maps to `scipy.integrate.solve_ivp` with method='RK45'. The argument order differs: MATLAB takes `(odefun, tspan, y0)`, scipy takes `(fun, t_span, y0)`. The converter handles the swap. Output access changes too — MATLAB gives `[t, y]` arrays; scipy wraps them in a `sol` object with `.t` and `.y` attributes.

MATLAB source11 lines
% Damped harmonic oscillator
% y'' + 0.2 y' + y = 0
f = @(t, y) [y(2); -0.2*y(2) - y(1)];

[t, y] = ode45(f, [0 30], [1; 0]);

figure
plot(t, y(:, 1), 'b-', 'LineWidth', 1.5);
xlabel('time'); ylabel('position');
title('Damped oscillator');
grid on;
Python output (converter-generated)16 lines · 1 flag
import matplotlib.pyplot as plt
from scipy import integrate

# Damped harmonic oscillator
# y'' + 0.2 y' + y = 0
f = lambda t, y: np.array([[y[1]], [-0.2*y[1], -, y[0]]])

t, y = solve_ivp(f, [0, 30], np.array([[1], [0]]))

plt.figure()
plt.plot(t, y[:, 0], 'b-', linewidth=1.5)
plt.xlabel('time')
plt.ylabel('position')
plt.title('Damped oscillator')
plt.grid(True)
Converter flags (1)
  • WARNINGLine 5: ode45 → solve_ivp — return format differs: MATLAB returns [t,y], scipy returns object with .t and .y attributes. Use method="RK45".
Implementation notes
scipy's solve_ivp returns a solution object. Access as `sol.t` and `sol.y[0]` instead of MATLAB's `t` and `y(:,1)`.
Try it on your own MATLAB

Free for 50 lines. Same converter that produced the Python above.

More examples like this, once a week

New canonical conversions and release notes from the converter. One email, no spam.