2

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.

Dev-iL
  • 23,742
  • 7
  • 57
  • 99
TEX
  • 2,249
  • 20
  • 43
  • Which version of MATLAB are you using? If you use array-multiply (`.*` or `bsxfun(@times, ...`) and provide a column vector (e.g. `a`-by-1) and a row vector (e.g. 1-by-`b`) you can get the result you want (of size a*b), up to transpose/`reshape`. – Dev-iL Oct 07 '18 at 14:23
  • Thanks. If I do `A.*B` I get `C` with `C(i)=A(i)*B(i)`. I have Matlab 2017b but I would like something working also on Matlab 2015b. – TEX Oct 07 '18 at 14:25

2 Answers2

4

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(:).').

Dev-iL
  • 23,742
  • 7
  • 57
  • 99
3

You can also calculate the outer product of the vectors, resulting in a matrix of your required terms:

C = A*B'; % Assuming A,B are column vectors here

And reshape the output afterward as stated. Not sure if more efficient though.

matanj
  • 362
  • 2
  • 10
  • 1
    Instead of assuming the shape, you can force them to be columns using `(:)`. Also, note that `transpose` is `.'` and **not** `'` (which is **conjugate** transpose). – Dev-iL Oct 07 '18 at 14:59