How to transform 3 nested for loops into a single loop

15 ビュー (過去 30 日間)
csk
csk 2014 年 8 月 1 日
回答済み: Anamika 2023 年 6 月 16 日
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
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?
csk
csk 2014 年 8 月 2 日
Geoff, Thanks for your suggestion. I think what you suggest is a good idea and will try it out. Yes, all matrices are pre-allocated.
This is a snippet of a bigger code which still runs decently fast. But it is also a much simpler problem than I will have to tackle eventually. So I was trying to figure out a way to condense the outer loops into a single loop and then try and use parfor.
I think one way to do that would something along the lines:
iterations = [n na tpts];
T = prod(iterations);
(par)for ix = 1:T
[h i t] = ind2sub(iterations,ix);
...;
end

サインインしてコメントする。

回答 (1 件)

Anamika
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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by