Stopping a for loop when certain values have been reached
조회 수: 50 (최근 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.
댓글 수: 0
채택된 답변
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)
display(values)
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)
display(values)
댓글 수: 4
Torsten
2022년 1월 16일
Theoretical result is
9*(1+1/2+1/3+1/4+1/5+1/6+1/7+1/8+1/9) = 25.46
Not so far apart.
Torsten
2022년 1월 17일
편집: Torsten
2022년 1월 17일
@Ben Hatrick Answer moved here:
This is a massive help, thanks so much!
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!