I would like to write a function which accepts as input the number of nested loops which the function will perform. For example, if the input parameter is 3, the function will perform 3 nested loops as follows :
for i=0:[any]
for j=0:[any]
for k=0:[any]
and if the input parameter is 2, it would be like this :
for i=0:[any]
for j=0:[any]
How can I implement this algorithm ?
Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.
In Python variables have function-wide scope which means that if two variables have the same name in the same scope, they are in fact one variable. Consequently, nested loops in which the target variables have the same name in fact share a single variable.
In short, you are right to do it. Note however that the variable is not supposed to retain its value between each loop. In such case, you may need to initialize it every time.
A nested loop is a loop within a loop, an inner loop within the body of an outer one. How this works is that the first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes.
As mentioned above, this problem can usually be solved by recursion.
Somehow like this:
function res = nestedloop_function(numLoops,remainingParams)
res = rec_function(numLoops,[],remainingParams);
end
function res = rec_function(numLoops, loopVars, remainingParams)
if numLoops == 0
res = whatever(loopVars, remainingParams);
return res;
end
for k = 1:[any]
loopVars = [loopVars,k];
res = rec_function(numLoops-1, loopVars, remainingParams);
end
end
If you don't want to have the overhead of passing remainingParams
and loopVars
you can think about declaring them as global
, but it is often better to avoid this...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With