Search code examples
matlabvectorvectorizationmultiplicationelementwise-operations

Multiply each element of a vector by each element of another vector


I have two very big column vectors, A and B, of size ax1 and bx1, respectively. I want to construct a vector C of size (b*a)x1 by computing A(i)*B(j) for each i and j. To illustrate what I mean:

clear
a=10^3;
b=10^3;
A=randn(a,1);
B=randn(b,1);
Ctemp=zeros(a,b);
for i=1:a
    for j=1:b
        Ctemp(i,j)=A(i)*B(j);
    end
end
C=reshape(Ctemp, a*b,1);

Question: is there a more efficient way to obtain C which avoid double looping? My actual a and b are bigger than 10^3.


Solution

  • This is a simple case of array multiplication that can benefit from implicit (or explicit) expansion:

    % Implicit (R2016b and newer):
    C = A(:) .* B(:).'; % optionally surround by reshape( ... , [], 1);
    
    % "Explicit" (R2007a and newer):
    C = bsxfun( @times, A(:), B(:).' );
    

    From there it's just a matter of reshaping, as you're already doing (D = C(:) or D = C(:).').