Optimizing a nested loop by summation

Does anyone have a suggestion on how I can optimize this nested loop? Is it possible to do this faster by just using sum? O, L, and W are of arbitrary size.
A = zeros(size(W));
for m = 1:size(O,1)
for pix = 1:NumPixels
A = A + O(m,pix) .* ( L(:,:,m,pix) ./ W ) ./ (sum( sum( L(:,:,m,pix) , 1 ) , 2 ) );
end
end

 Réponse acceptée

Andrei Bobrov
Andrei Bobrov le 15 Déc 2011
A = zeros(size(W));
for m = 1:size(O,1)
for pix = 1:NumPixels
L1 = L(:,:,m,pix);
A = A + O(m,pix)* L1./W / sum(L1(:));
end
end
without loop
s = size(L);
L1 = reshape(L,s(1),s(2),[]);
out = sum(bsxfun(@times,bsxfun(@rdivide,...
bsxfun(@rdivide,L1,W),sum(sum(L1,2))),reshape(O,1,1,[])),3);
ADD [8:27MDT 16.12.2011]
s = size(L);
L1 = reshape(L,prod(s(1:2)),[]);
A1 = reshape( bsxfun(@times,L1, 1./(W(:)*sum(L1)))*O(:),s(1),[])

1 commentaire

Kristoffer
Kristoffer le 15 Déc 2011
It looks good, but it's only marginally faster and demands more memory.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Mathematics dans Centre d'aide et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by