Stopping a for loop when certain values have been reached

49 次查看(过去 30 天)
I am running a for loop at want it to finish when a given number of values have all occured at least once. The ouputs of the for loop range from 1-9 (intagers) and I am saving the values into an array. I want to find how many iterations it takes for every number in this range to have occured at least once but am unsure how to code this. Any ideas would be greatly apprectiated.

采纳的回答

Voss
Voss 2022-1-16
编辑:Voss 2022-1-16
values = [];
n_tries = 1000;
for i = 1:n_tries
values(i) = randi(9);
if all(ismember(1:9,values))
break
end
end
display(i)
i = 27
display(values)
values = 1×27
2 1 9 5 9 3 1 4 4 2 7 3 9 2 5 6 1 2 1 2 7 3 5 1 7 6 8
It's probably better to use a while loop, so you don't have to set a maximum number of iterations (n_tries):
values = [];
i = 0;
while ~all(ismember(1:9,values))
i = i+1;
values(i) = randi(9);
end
display(i)
i = 16
display(values)
values = 1×16
7 8 2 6 6 5 7 4 5 9 3 4 3 7 2 1
  4 个评论
Torsten
Torsten 2022-1-17
编辑:Torsten 2022-1-17
@Ben Hatrick Answer moved here:
This is a massive help, thanks so much!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by