How to do fast matrix multiplication for each column of two matrices without loops?

I have two matrices A

and B

for which I want to do multiplication for each of my columns to create a new matrix. The first thing that comes to mind is

A = rand(4,3);
B = rand(4,3);

for J=1:SIZE(A,2)
    for jj=1:size(B,2)
        C(:,:,m) = A(:,j)*B(:,jj)' ;
        m = m+1 ;
    end
end

      

But I don't want to use loops for

that slow things down. Is there a way?

I am going to use matrices of the third dimension C

, the ones built by multiplying the columns A

and B

. Is it better to construct first C

and then use its 3-dimensional matrices in each loop, or just multiply in each loop?

+3


source to share


2 answers


One approach with bsxfun

-

N1 = size(A,1);
N2 = size(B,1);
C = reshape(bsxfun(@times,permute(A,[1 4 3 2]),permute(B,[4 1 2 3])),N1,N2,[])

      



You could avoid going to the fourth dimension as below, but it is still marginally slower than the previous 4D approach -

C = reshape(bsxfun(@times,permute(A,[1 3 2]),B(:).'),N1,N2,[])

      

+3


source


Alternatively to Divakar's answer, you can generate all 4-fold combinations of the row and column indices of the two matrices (c ndgrid

) and then calculate the products:



[m, p] = size(A);
[n, q] = size(B);
[mm, nn, qq, pp] = ndgrid(1:m, 1:n, 1:q, 1:p);
C = reshape(A(mm+(pp-1)*m).*B(nn+(qq-1)*n), m, n, p*q);

      

+1


source







All Articles