You can do the same thing as the OP's answer using bsxfun
(which actually works internally using a similar method, but is a little bit cleaner):
C = bsxfun(@times, A, permute(B, [3 1 2]));
This is also quite a bit faster (bsxfun
must do some magic internally - probably takes advantage of MATLAB's internal ability to do certain operations using multiple threads, or it might just be that permuting the smaller matrix is a lot faster, or some combination of similar factors):
>> N1 = 100; N2 = 20; N3 = 4; A = rand(N1, N2); B = rand(N2, N3);
>> tic; for n = 1:10000; C = repmat(A, [1, 1, size(B, 2)]) .* permute(repmat(B, [1, 1, size(A, 1)]), [3, 1, 2]); end; toc
Elapsed time is 2.827492 seconds.
>> tic; for n = 1:10000; C2 = bsxfun(@times, A, permute(B, [3 1 2])); end; toc
Elapsed time is 0.287665 seconds.
Edit: moving the permute
inside the repmat
shaves a little bit of time off, but it's still nowhere near as fast as bsxfun
:
>> tic; for n = 1:10000; C = (repmat(A, [1 1 size(B, 2)]) .* repmat(permute(B, [3 1 2]), [size(A, 1) 1 1])); end; toc
Elapsed time is 2.563069 seconds.