How can i speed up my nested for loops ?

1 view (last 30 days)
Robin Chang
Robin Chang on 1 Oct 2020
Answered: Jeff Miller on 2 Oct 2020
Hello everyone,
Could you please help to speed up my code? It is a nested for loops code and running very slow. Is there any way to speed up the computation? I am a Matlab beginner, i have tried to vectorize the code but failed. The code is here:
p0=0.02;
n=100;
c=5000;
for n1 = 38 : 52 ;
for w = 0.5: 0.01: 3.4 ;
for k1 = w+0.01: 0.25 : 7.5;
for k2 = 0.5: 0.25: 5.5;
for R = RLi : 600
for x = x1 : x2
% n2
d1 = floor((n1*x/c) + w*sqrt(n1*x/c*(1-x/c))) ;
d2 = ceil((n1*x/c) + k1*sqrt(n1*x/c*(1-x/c)))-1 ;
pps = binocdf(d2, n1, p0) - binocdf(d1, n1, p0);
n2=floor((n-n1)/pps);
% alfa
d3 = floor((n1*x/c) + w*sqrt(n1*x/c*(1-x/c)))+1 : ceil((n1*x/c)+k1*sqrt(n1*x/c*(1-x/c)))-1 ;
d4 = floor(((n1+n2)*x/c) + k2*sqrt((n1+n2)*x/c*(1-x/c)))- d3 ;
pa1= binopdf(0:floor(n1*x/c+w*sqrt(n1*x/c*(1-x/c))),n1,p0);
pa10=sum(pa1)
pa22 = binocdf(d4, n2, p0);
pa21 = binopdf(d3, n1, p0);
A = pra10 + sum(pra21.*pra22);
cdf0 = (1-A^(R))*binopdf(x,c,p0);
end
end
end
end
end
end
Thanks a lot.

Answers (1)

Jeff Miller
Jeff Miller on 2 Oct 2020
You can speed this up to some degree by rearranging the order of your for loops. For example, consider:
d1 = floor((n1*x/c) + w*sqrt(n1*x/c*(1-x/c))) ;
d2 = ceil((n1*x/c) + k1*sqrt(n1*x/c*(1-x/c)))-1 ;
pps = binocdf(d2, n1, p0) - binocdf(d1, n1, p0);
Of the looping variables, these lines only depend on n1, w, k1, and x, so you don't need to compute them again and again for all the different combinations of R and k2. That suggests an organization of loops something like:
for n1 = 38 : 52 ;
for w = 0.5: 0.01: 3.4 ;
for k1 = w+0.01: 0.25 : 7.5;
for x = x1 : x2
% n2
d1 = floor((n1*x/c) + w*sqrt(n1*x/c*(1-x/c))) ;
d2 = ceil((n1*x/c) + k1*sqrt(n1*x/c*(1-x/c)))-1 ;
pps = binocdf(d2, n1, p0) - binocdf(d1, n1, p0);
for k2 = 0.5: 0.25: 5.5;
for R = RLi : 600
...
I didn't look to see whether there are other analogous speed-ups involving d3, d4, etc, but hopefully this gives you one pattern of speed-up to look for.

Categories

Find more on Loops and Conditional Statements 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!