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.
% 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;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)
- 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).
References: MathWorks ode45 documentation · SciPy solve_ivp documentation
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.