How to multiply tensors in MATLAB without looping?

Alex Azazel picture Alex Azazel · Jul 19, 2015 · Viewed 7.1k times · Source

Suppose I have:

A = rand(1,10,3);
B = rand(10,16);

And I want to get:

C(:,1) = A(:,:,1)*B;
C(:,2) = A(:,:,2)*B;
C(:,3) = A(:,:,3)*B;

Can I somehow multiply this in a single line so that it is faster?

What if I create new tensor b like this

for i = 1:3
    b(:,:,i) = B;
end

Can I multiply A and b to get the same C but faster? Time taken in creation of b by the loop above doesn't matter since I will be needing C for many different A-s while B stays the same.

Answer

Luis Mendo picture Luis Mendo · Jul 19, 2015

Permute the dimensions of A and B and then apply matrix multiplication:

C = B.'*permute(A, [2 3 1]);