1

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.

0

1 Answer 1

3
  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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.