Nested loops

Here's a tricky one! How can I get rid of the loops?
for pix = 1:NumPixels
for ji = min(ShellNumbers(:,pix)):max(ShellNumbers(:,pix))
for jj = min(AngleNumbers(:,pix)):max(AngleNumbers(:,pix))
pos = ShellNumbers(:,pix) == ji & AngleNumbers(:,pix) == jj;
W(ji,jj) = W(ji,jj) + sum(PathLengths(pos,pix));
L(ji,jj,1,pix) = sum(PathLengths(pos,pix));
clear pos
end
end
end

Answers (1)

Jan
Jan on 15 Dec 2011
I cannot omit the loops, but it can be made faster:
% Pre-allocate!
s1 = max(ShellNumbers(:));
s2 = max(angleNumbers(:));
W = zeros(s1, s2);
L = zeros(s1, s2, 1, NumPixels); % What is "i"?!
for pix = 1:NumPixels
jjLow = min(AngleNumbers(:,pix));
jjHigh = max(AngleNumbers(:,pix));
for ji = min(ShellNumbers(:,pix)):max(ShellNumbers(:,pix))
a = ShellNumbers(:,pix) == ji;
for jj = jjLow:jjHigh
pos = a & AngleNumbers(:,pix) == jj;
B = sum(PathLengths(pos,pix));
W(ji,jj) = W(ji,jj) + B;
L(ji,jj,i,pix) = B; % What is "i"?!
end
end
end

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 15 Dec 2011

Community Treasure Hunt

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

Start Hunting!