Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a variable for nested loops?

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 ?

like image 728
MorTezaDM Avatar asked Sep 11 '14 11:09

MorTezaDM


People also ask

Can you create a variable in a for loop?

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.

Can nested for loops use the same variable?

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.

Do you have to initialize a variable in a for loop?

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.

How do you create nested loops?

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.


1 Answers

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...

like image 138
matheburg Avatar answered Oct 18 '22 20:10

matheburg