numpy multidimensional (3d) matrix multiplication
<p>I get two 3d matrix A (32x3x3) and B(32x3x3), and I want to get matrix C with dimension 32x3x3. The calculation can be done using loop like:</p>

<pre><code>a = numpy.random.rand(32, 3, 3)
b = numpy.random.rand(32, 3, 3)
c = numpy.random.rand(32, 3, 3)

for i in range(32):
    c[i] = numpy.dot(a[i], b[i])
</code></pre>

<p>I believe there must be a more efficient one-line solution to this problem. Can anybody help, thanks.</p>

<p>You could do this using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a>:</p>

<pre><code>In [142]: old = orig(a,b)

In [143]: new = np.einsum('ijk,ikl-&gt;ijl', a, b)

In [144]: np.allclose(old, new)
Out[144]: True
</code></pre>

<p>One advantage of using <code>einsum</code> is that you can almost read off what it's doing from the indices: leave the first axis alone (<code>i</code>), and perform a matrix multiplication on the last two <code>(jk,kl-&gt;jl)</code>).</p>

python matrix multidimensional-array matrix-multiplication