Search code examples
matlabmatrixmatrix-multiplicationcomplex-numberstensor

Multiply n vectors of length p by n matrices of size pxp


I have n complex vectors of length p that I want to multiply by n complex matrices of size p-by-p. I am looking for the most efficient way to do this in MATLAB. If it matters, I am imagining that n is large and p is small.

An example using a loop (which I would like to avoid) is shown below.

N = 1e4;
p = 5;
A = randn(p, N); % N vectors of length p
B = randn(p, p, N); % N matrices of size pxp

C = zeros(p, N); 
for k = 1:N
    C(:, k) = B(:, :, k) * A(:, k);
end

It's been suggested that I might be able to achieve this efficiently using tensor functions, but I haven't been able to figure that out.


Solution

  • Here's a way using implicit expansion:

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

    For old Matlab versions (before R2016b) you need to rewrite it with bsxfun:

    C = permute(sum(bsxfun(@times, B, permute(A, [3 1 2])), 2), [1 3 2]);