2

I already have a N_1 x N_2 matrix A, and a N_2 x N_3 matrix B.

I want to create a N_1 x N_2 x N_3 matrix C, such that C(i,j,k) = A(i,j)*B(j,k).

I was wondering if it is possible to create C using some Matlab operation, instead of doing it element by element?

4

2 回答 2

4

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.
于 2013-05-03T08:15:04.437 回答
2

Rather clumsy, but it seems to work:

C = repmat(A, [1, 1, size(B, 2)]) .* permute(repmat(B, [1, 1, size(A, 1)]), [3, 1, 2]);
于 2013-05-03T07:36:16.090 回答