Multiply matrices layer by layer

160 views Asked by At

I want to do this without loops:

% A ~ 4x2x3; B ~ 4x3x2; C ~ 4x2x2;
for i=1:4
  C(i,:,:) =  squeeze(A(i,:,:))*squeeze(B(i,:,:));
end

Thanks!

1

There are 1 answers

0
Eitan T On BEST ANSWER

Haven't benchmarked this (so this is not guaranteed to be faster), but here goes:

[L, ma, na] = size(A);
[L, mb, nb] = size(B);
AX = reshape(permute(A, [2 1 3]), [], na);
BX = reshape(permute(B, [2 3 1]), mb, []);
CX = reshape(permute(reshape(AX * BX, ma, L, nb, L), [1 3 2 4]), ma, nb, []);
C = permute(CX(:, :, 1:L + 1:end), [3 1 2]);

Note that you might also run into memory problems if A and B are large (in which case you'll have to resort to loops).