Efficient matrix multiplication in Matlab
<p>I have two matrices, <code>A</code> (N by K) and <code>B</code> (N by M) and I would like to concentrate <code>A</code> and <code>B</code> into a tensor <code>C</code> (N by K by M) where <code>C(n,k,m) = A(n,k) * B(n,m)</code>. I know how to do it in python like    </p>

<pre><code>C = B[:,numpy.newaxis,:] * A[:,:,numpy.newaxis]
</code></pre>

<p>Can anyone please tell me the matlab code that does the same thing efficiently?</p>

<p>Take advantage of the implicit expansion feature of <a href="https://www.mathworks.com/help/matlab/ref/bsxfun.html" rel="nofollow"><code>bsxfun</code></a>. Use <a href="https://www.mathworks.com/help/matlab/ref/permute.html" rel="nofollow"><code>permute</code></a> to have your <code>B</code> as an Nx1xM matrix:</p>

<pre><code>C = bsxfun(@times, A, permute(B, [1, 3, 2]));
</code></pre>

<p>And from MATLAB <strong>R2016b</strong> onward, you can get the same result in this way:</p>

<pre><code>C = A * permute(B, [1, 3, 2]);
</code></pre>

python matlab numpy matrix matrix-multiplication