title: Vectorizing NumPy covariance for 3D array
body: <p>I have a 3D numpy array of shape <code>(t, n1, n2)</code>:</p>
  
  <pre><code>x = np.random.rand(10, 2, 4)
  </code></pre>
  
  <p>I need to calculate another 3D array <code>y</code> which is of shape <code>(t, n1, n1)</code> such that: </p>
  
  <pre><code>y[0] = np.cov(x[0,:,:])
  </code></pre>
  
  <p>...and so on for all slices along the first axis.</p>
  
  <p>So, a loopy implementation would be:</p>
  
  <pre><code>y = np.zeros((10,2,2))
  for i in np.arange(x.shape[0]):
      y[i] = np.cov(x[i, :, :])
  </code></pre>
  
  <p>Is there any way to vectorize this so I can calculate all covariance matrices in one go? I tried doing:</p>
  
  <pre><code>x1 = x.swapaxes(1, 2)
  y = np.dot(x, x1)
  </code></pre>
  
  <p>But it didn't work.</p>