3
votes

I have two matrices A and B for which I want to do a multiplication for each of their columns to produce a new matrix. The first thing cross my 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 for loops which makes it slow. Is there any way?

I am going to use the matrices of third dimension of C, the ones which are built by multiplication of columns of A and B, Is it better to first build the C and then use its 3rd dimension matrices in each loop or just do the multiplication in each loop?

2

2 Answers

3
votes

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 4th dimension as listed next, but it's still marginally slower than the earlier 4D approach -

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

As an alternative to Divakar's answer, you can generate all 4-fold combinations of row and column indices of the two matrices (with ndgrid) and then compute 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);