Hi, How to write the code with random number of iterations?

Hi, there are two parameters, n and d. We repeat n times experiments. In each experiment, there are d possibilities.
So there are d^n combinations.
So I have to write like this:
for i=1:d
for j=1:d
..... until the nth for
and then
end
end ...
But I do not know the values of n and d.

Answers (2)

You can avoid the nested FOR loops by using a vector as counter and one WHILE loop:
n = 4;
d = 5;
index = ones(1, n);
doRun = true;
while doRun
disp(index); % insert your operations here
% Update the index:
doRun = false;
for k = n:-1:1
index(k) = index(k) + 1;
if index(k) <= d
doRun = true;
break; % Leave "for k" loop
end
index(k) = 1; % Reset k.th counter
end
end
You can do it using eval function
d=10
n=5
out=0
s1=sprintf('for k%d=1:%d,',[1:n;repmat(d,1,n)]); % The n first for loop
s2='out=out+1,' % your calculations
s3=repmat(',end',1,n) % the n end
s=[s1 s2 s3]
eval(s) % to execute your for loop
Maybe there is another alternative: a function that calls itself n time

2 Comments

Thank you Azzi. This does help me.
EVAL is always a bad solution. Injecting variables dynamically in a workspace slows down the JIT massively.

Sign in to comment.

Asked:

on 8 Sep 2013

Community Treasure Hunt

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

Start Hunting!