Vectorization of outer product calculation

Viewed 369

I have a matrix A of size KxN. I want to take the outer product between each column of this matrix with itself, creating a new matrix of size KxKxN. I can do this iteratively by doing:

N = 5;
K = 3;

A = rand(K,N);

nA = zeros(K,K,N); 
for n=1:N
    nA(:,:,n) = nA(:,:,n) + A(:,n)*A(:,n)';
end

or faster by writing a mex-file (when N is large). However, I have not yet figured out if I can do this in a vectorized fashion. Any ideas?

1 Answers
Related