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

 Akzeptierte Antwort

Andrei Bobrov
Andrei Bobrov am 15 Dez. 2011

0 Stimmen

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 Kommentar

Kristoffer
Kristoffer am 15 Dez. 2011
It looks good, but it's only marginally faster and demands more memory.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Mathematics finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by