Search code examples
pythonmatplotlibscipyodescientific-computing

Solving and plotting ODE with dependent parameters


I'm working on a bit of code where I have the following system of equations here. The issue being that I'd very much like to solve for multiple values of k as well as have a phase plane/quiver plot for each value of k. Can someone please help me? This is what I have so far for the solver:

import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint

def model(X, t):
    x = X[0]
    y = X[1]
    dxdt = k*x - y
    dydt = x + y
    return [dxdt, dydt]
#Initial state 
X0 = [1,1]

#Time
t = np.linspace(0,10)

X = odeint(model, X0, t)

And this is what I have so far for plotting:

x = X[:,0]
y = X[:,1]

plt.plot(x,y)

Please note, I'm not trying to simply solve the system! I'm trying to solve it with multiple values changing (k) and plotting the resulting equations.


Solution

  • You have to iterate over k, and pass the value as an additional parameter:

    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.integrate import odeint
    
    def model(X, t, k):
        x = X[0]
        y = X[1]
        dxdt = k*x - y
        dydt = x + y
        return [dxdt, dydt]
    #Initial state 
    X0 = [1,1]
    
    #Time
    t = np.linspace(0,10)
    Ks = np.linspace(-1, 1, 10)
    
    for kix in Ks:
        X = odeint(model, X0, t, args=(kix,))
        x = X[:,0]
        y = X[:,1]
        plt.plot(x,y)
    plt.show()
    

    enter image description here