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

 Accepted Answer

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 Comment

It looks good, but it's only marginally faster and demands more memory.

Sign in to comment.

More Answers (0)

Categories

Find more on Mathematics in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!