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

I have a problem that I hope can be easily resolved. A is the NG matrix, B is the NG matrix. The goal is to get the matrix C

enter image description here

which is equal to multiplying each transposed column A by each row of B and summing the resulting matrices; the total number of such matrices before summation is NN, their size is GG. This can easily be done in MatLab with two circuits:

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 rather slow.

So my question is: is there a more efficient way to calculate the matrix C in Matlab?

thanks

+6
source share
3 answers

If you write all this for two 3 × 3 matrices, you will find that the operation is basically equal to this:

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

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

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

(coefficient ≈ 4000 between the fastest and slowest method ...)

+7
source

I think this should significantly improve performance.

 C = zeros(G); for n = 1:N C = C + sum(A,1)'*B(n,:); end 

You avoid one cycle, and also avoid running out of memory problems. According to my benchmarking, this is about 20 times faster than a two-cycle approach. (Note, I had to navigate in Octace, since I do not have MATLAB on this PC).

+3
source

Use bsxfun instead of loops, and then sum twice:

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

All Articles