CodeFusionMobile
CodeFusionMobile

Reputation: 15130

Vectorize sum of outer products in matlab

Any ideas how to vectorize this code? The result S should be 3x3.

%PNorm is n x 3
S = zeros(3,3,n);
%TODO vectorize
for i = 1:n
    S(:,:,i) = Pnorm(i,:)'*Pnorm(i,:);
end
S = sum(S, 3);

Upvotes: 0

Views: 140

Answers (2)

Shai
Shai

Reputation: 114976

For explicit computation you can trade the loop for bsxfun:

S = bsxfun( @times, permute( Pnorm, [2 3 1]), permute( Pnorm, [3 2 1] ) );
S = sum( S, 3 );

However, for an efficient computation see EitanT's answer.

Upvotes: 0

Eitan T
Eitan T

Reputation: 32930

Is there any reason not to do:

S = Pnorm' * Pnorm;

Hmm?

Upvotes: 2

Related Questions