Reputation: 394
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?
Upvotes: 2
Views: 484
Reputation: 35080
If you reshape your array to size [K,1,N]
and [1,K,N]
(i.e. inject singleton dimensions in the appropriate positions), you only need to multiply them using array broadcasting.
Newer versions of MATLAB with implicit broadcasting:
nA_bcast = reshape(A,[1,K,N]).*reshape(A,[K,1,N])
Older versions of MATLAB with the help of bsxfun
:
nA_bsxfun = bsxfun(@times, reshape(A,[1,K,N]),reshape(A,[K,1,N]))
The three relevant arrays (i.e. nA
, nA_bcast
and nA_bsxfun
) are all the same. Side note: A'
will be the adjoint, you probably mean A.'
for transpose.
Upvotes: 4