# [Matlab] Help! How to create n amount of loops?

#### TheNewbie

##### New Member
Hi, please help me out. I am trying to figure out how to write a number of loops an n amount of times, and I just don't manage.

Say that, for n = 10, I want to create 10 loops, each from 0 to 1.

for e1=0:1
for e2=0:1
for e3=0:1
for ...
for ...
for ...
for ...
for ...
for ...
for ...
Expression=...
end
end
end
end
end
end
end
end
end
end

Is there a simple way to do this, so that I can vary the value of n each time I am running the code?

#### wandatheavenger

##### New Member
What kind of expression are you looking to put in there? Depending on what you want to do, there may be a way around it. If all of the loops must be nested, you can set a limit to your n size and add an if statement at every step. So for step 'p' you would have a statement to evaluate whether n >= p before proceeding.

A possible downside of this, depending on the length of your expression, could be a really long bit of code, as each if would have to be accompanied by an else statement that contained the expression.

#### TheNewbie

##### New Member
The expression you ask for is something like:

P=X*P(Y=e1)P(Y=e2)...P(Y=en)

so yes, the expression will be huge. I'm not sure I understand what you mean... #### wandatheavenger

##### New Member
I don't know if I understand what that expression is doing, but I'll try to help anyway. What I suggest in my previous post is that for every 'for' statement, you add an 'if' statement to see if you want to continue. So, if you built it for a maximum n of 3, it might look something like this:

for e1 = 0:1
if n > 1
for e2 = 0:1
if n > 2
for e3 = 0:1
P=X*P(Y=e1)P(Y=e2)P(Y=e3);
end;
else
P=X*P(Y=e1)P(Y=e2);
end;
end;
else
P=X*P(Y=e1);
end;
end;

At level 1, the expression checks to see if n is greater, if so, it moves on up a level, if not, it runs the expression.

Depending on what exactly you're trying to do with your expression, though, there might be another way. For example, if you must have all of your 'for' loops inside of other 'for' loops, and each goes from 0 to 1, you are running through 2^n cycles. Knowing this, you might be able to have a loop that runs from 1 to 2^n to do what you need instead. If, however, you just need to run n independent loops that go from 0 to 1, you can use the eval command.