Search code examples
pythonmatlabode

Solving ODE in python


In MATLAB I am solving this ode as:

B = [0 0 -5]'; 
y0 =[0 -5 0 5 0 0]';
f = @(t,y) [y(4:6); (q/m)*cross(y(4:6),B)];
[t,y] = ode45(f,[0 100],y0);

I've been reading previous answers about how to solve ODEs in Python and how to fit the MATLAB code to corresponding Python code but, when I try to solve the same ODE as:

f=lambda t,y: np.array([y(np.arange(4,6)),(q/m)*np.cross(y(np.arange(4,6)),B)])
sol =solve_ivp(f, np.array([0 100]), y0)

I get an error message(line 454, in solve_ivp solver = method(fun, t0, y0, tf, vectorized=vectorized, **options))

I also tried:

sol = integrate.odeint(f, np.array([0 100]), y0)

without any luck.


Solution

    1. y(4:6) in MATLAB is not y(np.arange(4,6)) in Python.

      • In MATLAB, y(4:6) gets the 4th to 6th elements from array y.
      • In Python, that should be y[3:6] (square brackets; 3 instead of 4 because Python is 0-indexed; 6 instead of 5 because Python's right bound is non-inclusive).
    2. In the MATLAB f, the vectors are joined vertically (semicolon), so in Python they should be stacked vertically with vstack().

    3. Python lists require commas. In the sol line, [0 100] needs to be [0, 100].

    You probably want something like this:

    f = lambda t, y: np.vstack([y[3:6], (q/m) * np.cross(y[3:6], B)])
    sol = solve_ivp(f, np.array([0, 100]), y0)