How to multiply each column of matrix A by each row of matrix B and sum resulting matrices in Matlab?

matlab, matrix, matrix-multiplication, performance

Solution

If you write it all out for two 3×3 matrices, you'll find that the operation basically equals this:

C = bsxfun(@times, sum(B), sum(A).');

Running each of the answers here for `N=50`, `G=100` and repeating each method 100 times:

Elapsed time is 13.839893 seconds. %// OP's original method
Elapsed time is 19.773445 seconds. %// Luis' method
Elapsed time is 0.306447 seconds.  %// Robert's method
Elapsed time is 0.005036 seconds.  %// Rody's method

(a factor of ≈ 4000 between the fastest and slowest method...)

Problem

I have a problem which I hope can be easily solved. A is a NG matrix, B is NG matrix. The goal is to get matrix C which is equal to multiplying each column of transposed A by each row of B and summing resulting matrices; total number of such matrices before summing is NN, their size is GG This can be easily done in MatLab with two for-loops: ``` N=5; G=10; A=rand(N,G); B=rand(N,G); C=zeros(G); for n=1:1:N for m=1:1:N C=C+A(m,:)'*B(n,:); end end ``` However, for large matrices it is quite slow. So, my question is: is there a more efficient way for calculating C matrix in Matlab? Thank you

Original source