user2324712
user2324712

Reputation: 435

How would you remove the loop from this matlab code

Given that we have:

I would like to evaluate the following code without a loop: (or in a way faster way)

out = zeros(1,numSamples);
for i = 1:numSamples
    res = sum(repmat(B - x(i,:), numSamples, 1)*A.*(x - repmat(x(i,:), numSamples, 1)), 2).^2;
    out(i) = var(res);
end

If you have other suggestions on a faster improvement of the above, it is also more than welcome.

Upvotes: 2

Views: 70

Answers (1)

Divakar
Divakar

Reputation: 221514

You can bsxfun those piece-by-piece for a vectorized solution -

P1 = bsxfun(@minus,B,x)*A;
P2 = bsxfun(@minus,x,permute(x,[3 2 1]));
out = var(squeeze(sum(bsxfun(@times,P1,P2),2)).^2.');

Partially vectorized approach -

P = (bsxfun(@minus,B,x)*A).';  %//'
out = zeros(1,numSamples);
for i = 1:numSamples
    out(i) = var((bsxfun(@minus,x,x(i,:))*P(:,i)).^2);
end

Upvotes: 7

Related Questions