How to transform 3 nested for loops into a single loop
16 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Geoff Hayes
el 2 de Ag. de 2014
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?
Respuestas (1)
Anamika
el 16 de Jun. de 2023
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 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!