Hi, How to write the code with random number of iterations?
Show older comments
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)
Jan
on 8 Sep 2013
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
1 Comment
Azzi Abdelmalek
on 8 Sep 2013
Amazing approach! +1
Azzi Abdelmalek
on 8 Sep 2013
Edited: Azzi Abdelmalek
on 8 Sep 2013
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
Categories
Find more on Design Condition Indicators Interactively in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!