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.