Search code examples
pythoncontrolslinear-algebraode

How to solve matrix differential equations in Python?


dx/dt = Ax where A, x belongs to n x n array. I have tried using solve_ivp and odeint features in scipy.integrate, but both these work only with n x 1 arrays.


Solution

  • The integrators expect that the ODE function consumes a flat, one-dimensional array as the state variable and returns an equally flat derivatives vector. This input array contains the entries of the matrix. To perform matrix operations on it, you need to build a matrix from the flat input array, and in the end reverse that for the output of the derivatives function

    x0 = x0.reshape(-1);         # make data 1-dimensional
    def odefun(t,x):
        x=x.reshape([n,n]);      # restore to matrix form
        dx=A.dot(x);             # perform matrix operations
        return dx.reshape(-1);   # return 1-dimensional vector
    
    sol = solve_ivp(odefun, [t0, tf], x0)