How to vectorize the formation of many external products of rank-1?

Is it possible to vectorize the loop below? Each iteration in the loop forms an external product, then it balances and stores the result as a column in the matrix. He suggested that m is large (e.g., 1e4) and s is small (e.g., 10).

 % U and V are m-by-s matrices A = zeros(s^2, m); % preallocate for k = 1:m Ak = U(k,:)' * V(k,:); Ak = (Ak + Ak')/2; A(:, k) = Ak(:); end 

Edit

Below is a comparison of three different methods: iteration over large dimension m , iteration over small dimension s and a solution based on bsxfun (the accepted and fastest answer).

 s = 5; m = 100000; U = rand(m, s); V = rand(m, s); % Iterate over large dimension tic B = zeros(s^2, m); for k = 1:m Ak = U(k,:)' * V(k,:); Ak = (Ak + Ak')/2; B(:, k) = Ak(:); end toc % Iterate over small dimension tic A = zeros(s, s, m); for i = 1:s A(i,i,:) = U(:, i) .* V(:, i); for j = i+1:s A(i,j,:) = (U(:,i).*V(:,j) + U(:, j).*V(:, i))/2; A(j,i,:) = A(i,j,:); end end A = reshape(A, [s^2, m]); toc % bsxfun-based solution tic A = bsxfun( @times, permute( U, [1 3 2] ), permute( V, [ 1 2 3 ] ) ); A = .5 * ( A + permute( A, [1 3 2] ) ); B = reshape( A, [m, s^2] )'; toc 

Here is a time comparison:

 Elapsed time is 0.547053 seconds. Elapsed time is 0.042639 seconds. Elapsed time is 0.039296 seconds. 
+4
source share
1 answer

Use bsxfun (as this is done with great pleasure):

 % the outer product A = bsxfun( @times, permute( U, [1 3 2] ), permute( V, [ 1 2 3 ] ) ); % symmetrization A = .5 * ( A + permute( A, [1 3 2] ) ); % to vector (per product) B = reshape( A, [ms^2] )'; 

Test results (my car):

  • The original approach (iteration over the big ball):

      Elapsed time is 0.217695 seconds. 
  • The β€œnew” approach (iteration over the smaller one):

      Elapsed time is 0.037538 seconds. 
  • bsxfun to bsxfun with bsxfun :

      Elapsed time is 0.021507 seconds. 

As you can see, bsxfun takes ~ 2/3 - 1/2 of the time of the fastest cycle ...

Isn't it fun with ?

+1
source

Source: https://habr.com/ru/post/1490489/


All Articles