Solving two sets of coupled ODEs via matrix form in Python
<p>I want to solve a coupled system of ODEs in matrix form for two sets of variable (i.e. {y} and {m}) which has such a form:</p>

<blockquote>
  <p>y'_n = ((m_n)**2) * y_n+(C * y)_n  ,   m'_n=-4*m_n*y_n  </p>
</blockquote>

<p>where <code>C</code> is a matrix, <code>[2 1, -1 3]</code>.  </p>

<p>On the other hand I want to solve these equations:</p>

<blockquote>
  <p>y'1= m1 ** 2 * y1 + 2 * y1 + y2<br>
   y'2= m2 ** 2 * y2 - y1 + 3 * y3<br>
   m'1= -4 * m1 * y1 ,<br>
  m'2= -4 * m2 * y2<br>
   y1(0)=y2(0)=-15. and m1(0)=m2(0)=0.01</p>
</blockquote>

<p>to finally be able to plot ys and ms versus time via matrix form. I wrote the following program:</p>

<pre><code>import numpy as np
from pylab import plot,show
from scipy.integrate import odeint

C=np.array([[2,1],[-1,3]])
dt=0.001
def dy_dt(Y,time):
 y,m=Y
 m=m+dt*(-4.*m*y)
 dy=m**2*y+np.dot(C,y)
 return dy

m_init=np.ones(2)*0.01
y_init=np.ones(2)*-15.
time=np.linspace(0,4,1/dt)
y0=np.hstack((y_init, m_init))
y_tot=odeint(dy_dt,y0,time)



plot(time,y_tot[0])#y_1
plot(time,y_tot[1])#y_2
plot(time,y_tot[2])#m_1
plot(time,y_tot[3])#m_2
show()
</code></pre>

<p>but I encountered the following error:</p>

<pre><code> y,m=Y   
 ValueError: too many values to unpack 
</code></pre>

<p>Can anybody help me!</p>

<p><code>odeint</code> works with one-dimensional arrays.  In your function <code>dy_dt</code>, <code>Y</code> will be passed in as a one-dimensional numpy array with length 4.  To split it into <code>y</code> and <code>m</code>, you can write</p>

<pre><code>y = Y[:2]
m = Y[2:]
</code></pre>

<p>The function <code>dy_dt</code> must also return a sequence of length 4, containing [y[0]', y[1]', m[0]', m[1]'] (i.e. the derivatives of the four quantities).  It looks like your function currently returns just two quantities in <code>dy</code>, so you will have to fix that, too.</p>

<p>This line</p>

<pre><code>m=m+dt*(-4.*m*y)
</code></pre>

<p>looks suspiciously like Euler's method.  That's not what you want here.  Based on what you wrote in the question, you could write:</p>

<pre><code>dm = -4. * m * y
</code></pre>

<p>Then you could return <code>np.hstack((dy, dm))</code>.</p>

<p>To summarize, you can write <code>dy_dt</code> like this:</p>

<pre><code>def dy_dt(Y, time):
    y = Y[:2]
    m = Y[2:]
    dy = m**2 * y + np.dot(C, y)
    dm = -4 * m * y
    return np.hstack((dy, dm))  # or:  return [dy[0], dy[1], dm[0], dm[1]]
</code></pre>

python numpy scipy odeint