Stopping a for loop when certain values have been reached

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 日

0 投票

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 件のコメント

Ben Hatrick
Ben Hatrick 2022 年 1 月 16 日
This is perfect thank you so much. Lastly, how would i run this trail say 100 times and find the mean i value? i.e the average number of iterations needed to have all the values 1-9.
Voss
Voss 2022 年 1 月 16 日
編集済み: Voss 2022 年 1 月 16 日
n_trials = 100;
n_iterations_needed = zeros(1,n_trials);
for j = 1:n_trials
values = [];
i = 0;
while ~all(ismember(1:9,values))
i = i+1;
values(i) = randi(9);
end
n_iterations_needed(j) = i;
end
n_avg = mean(n_iterations_needed);
display(n_iterations_needed)
n_iterations_needed = 1×100
13 31 26 21 43 39 56 37 18 13 22 27 24 13 25 25 39 21 22 30 29 22 21 19 18 15 25 36 28 26
display(n_avg)
n_avg = 25.9300
Torsten
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
Torsten 2022 年 1 月 17 日
編集済み: Torsten 2022 年 1 月 17 日
@Ben Hatrick Answer moved here:
This is a massive help, thanks so much!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2022 年 1 月 16 日

編集済み:

2022 年 1 月 17 日

Community Treasure Hunt

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

Start Hunting!

Translated by