How can i speed up my nested for loops ?

조회 수: 2 (최근 30일)
Robin Chang
Robin Chang 2020년 10월 1일
답변: Jeff Miller 2020년 10월 2일
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.

답변 (1개)

Jeff Miller
Jeff Miller 2020년 10월 2일
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by