Vectorize the sum of outer products of corespondin

2019-07-13 09:40发布

问题:

Suppose I have two matrices A and B which are made up of column vectors as follows.

A = [a_1,a_2,...,a_N];
B = [b_1,b_2,...,b_N];

Is there any way to vectorize the calculation of the sum of outer products for every column in A with the corresponding column in B. Here is my non-vectorized solution.

S = zeros(size(A,1), size(B,1));
for n=1:N
    S = S + A(:,n)*B(:,n)';   % S = S + a_n * b_n'
end

Any help would be greatly appreciated.

回答1:

you are not clear on what N is, but I assume that N = number of column vectors - which means you are simply doing A * B'

A = rand(3,4);
B = rand(3,4);
N = size(A,2);
S = zeros(size(A,1), size(B,1));
for n=1:N
  S = S + A(:,n)*B(:,n)';   % S = S + a_n * b_n'
end
%Check that you are doing A*B'
S == A*B'
>> ans =

 1     1     1
 1     1     1
 1     1     1