How to transform 3 nested for loops into a single loop
조회 수: 10 (최근 30일)
이전 댓글 표시
Hi, I was wondering if there is any know algorithm to convert nested for loops into a single loop. In particular, I am running a code where the bottle neck seems to come from the following part of the code
for t=1:tpts
for i = 1:na
for h=1:n
tW1 = zeros(na,1)+ (-1.00e12);
for j = 1:na
if (domw(h)+pmt(t)-doma(j)+(1+ra)*doma(i)>0)
tW1(j) = log(domw(h)+pmt(t)-doma(j)+(1+ra)*doma(i)) + beta*((1-delta)*Wt1(t,j,h) + delta*Ut1(t,j));
end
end
[val,index] = max(tW1(:));
aprimeW(t,i,h)=doma(index);
W1(t,i,h)=val;
end
end
end
Thank you in advance!
댓글 수: 2
Geoff Hayes
2014년 8월 2일
I wonder rather than re-initializing tW1 at each iteration of h, if you could just reset the values instead. So your first line of code (before the first for loop) could be just
tW1 = zeros(na,1)+ (-1.00e12);
for t=1:tpts
% etc.
And then the first line of code within the h loop could be
tW1(:) = -1.00e12
As well, have you pre-allocated memory to aprimeW and W1?
답변 (1개)
Anamika
2023년 6월 16일
Here's an example of how to transform 3 nested for loops into a single loop
% Original
for i = 1:n
for j = 1:m
for k = 1:l
% Code Block
end
end
end
% modified into single loop
for idx = 1:n*m*l
i = mod(idx-1, n) + 1;
j = mod(floor((idx-1)/n), m) + 1;
k = floor((idx-1)/(n*m)) + 1;
% Code Block
end
We can transform these nested for loops into a single loop using a linear index that ranges from 1 to n* m* l then we can use the mod and floor functions to calculate the equivalent values of i, j, and k at each iteration of the loop, the order of the indices in the mod and floor functions matches the order of the nested loops (i, j, and k), this ensures that the nested loops and the single loop iterate over the same values.The code block inside the single loop is identical to the code block inside the nested loops
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!