Speed up multilple matrix products with numpy
<p>In python I have 2 three dimensional arrays: </p>

<p><code>T</code> with size <code>(n,n,n)</code></p>

<p><code>U</code> with size <code>(k,n,n)</code></p>

<p><code>T</code> and <code>U</code> can be seen as many 2-D arrays one next to the other. I need to multiply all those matrices, ie I have to perform the following operation:</p>

<pre><code>for i in range(n):
        H[:,:,i] =  U[:,:,i].dot(T[:,:,i]).dot(U[:,:,i].T)
</code></pre>

<p>As <code>n</code> might be very big I am wondering if this operation could be in some way speed up with numpy.</p>

<p>Carefully looking into the iterators and how they are involved in those dot product reductions, we could translate all of those into one <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a> implementation like so -</p>

<pre><code>H = np.einsum('ijk,jlk,mlk-&gt;imk',U,T,U)
</code></pre>

python numpy