invalid index to scalar variable error in solve of system of 5 ode in python

65 Views Asked by At

I wrote the following code to solve 5 differential equations in Python. But I get the following error: invalid index to scalar variable I was very tried and searched, but I did not find that where is it? Can anyone tell me where should I fix?

from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt 
def ode(x, t):
    vx = x[0]
    vy = x[1]
    x = x[2]
    y = x[3]
    a = x[4]
    dvxdt = -0.2*(np.cos(a))/(x**2+y**2)
    dvydt = -0.2*(np.sin(a))/(x**2+y**2)
    dxdt = vx
    dydt = vy
    dadt = (x*vy - y*vx)*((np.cos(a))**2)/(x**2)
    return [dvxdt, dvydt, dxdt, dydt, dadt]
x0 = [-1.7, 1, 5, 2, 0.5]
t = np.linspace(0,15,1000)
x = odeint(ode,x0,t)
vx = x[:,0]
vy = x[:,1]
x = x[:,2]
y = x[:,3]
a = x[:,4]

plt.semilogy(x,y)
plt.show()
1

There are 1 best solutions below

0
Warren Weckesser On

The problem is this line in the function ode:

    x = x[2]

You have reassigned the variable x, so after this statement is executed, x is the scalar that had been stored in the original array x. You'll have to use a different name for the scalar or for the ode array parameter.

You have a similar problem later in the script:

x = x[:,2]