numericaloptimization

MATLAB ode45 to Python: Damped Oscillator

Convert MATLAB ode45 to Python with scipy.integrate.solve_ivp. Compare the damped-oscillator source, generated code, and solver output differences.

MATLAB's `ode45` is commonly ported to `scipy.integrate.solve_ivp` with method `RK45`. The call arguments are in the same general order: function, time span, initial state. The return contracts differ: MATLAB returns `[t, y]`, while SciPy returns an `OdeResult` whose `t` is one-dimensional and whose `y` has shape (number of states, number of time points). The converter warns about that mismatch; its generated draft still needs a manual return-value and shape fix.

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)19 lines · 1 flag
import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate

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

_sol = integrate.solve_ivp(lambda _t, _y: np.ravel(f(_t, _y)), [0, 30], np.ravel(np.vstack([1, 0])), method='RK45')
t = _sol.t
y = _sol.y.T

plt.figure()
plt.plot(t, y[:, 0:0+1], 'b-', linewidth=1.5)
plt.xlabel('time')
plt.ylabel('position')
plt.title('Damped oscillator')
plt.grid(True)
Converter flags (1)
  • TOOLBOXLine 5: ode45 returns one OdeResult, not a [t, y] pair - unpacked into `t` and `y`, with `y` transposed to MATLAB's orientation (rows = time steps).
Implementation notes
This one runs as emitted. Three things had to be adapted, and all three come from the same place - MATLAB state vectors are columns, SciPy wants 1-D: np.ravel on the initial state, np.ravel on whatever the derivative returns, and method='RK45' to match ode45 rather than taking SciPy's default. solve_ivp also returns one OdeResult instead of a [t, y] pair, so the result is unpacked into _sol and y is transposed back to MATLAB's orientation, rows = time steps.

References: MathWorks ode45 documentation · SciPy solve_ivp documentation

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.