Creating functions to use inside for loops - birthday paradox simulation

4 ビュー (過去 30 日間)
Katherine Sadler
Katherine Sadler 2022 年 4 月 24 日
コメント済み: Voss 2022 年 4 月 24 日
Hi all, this is an assignment for the birthday paradox simulation. The code below is working fine but I think we are meant to turn parts of the code into user-defined functions and call the functions instead of having it all written out. In the GUI simulation the user inputs both N for realisations and k1 for maximum group size. The functions we are meant to have separate are randi() and checking the random numbers to see if there is a match (ind = find(rdie == b);). The problem is I don't know how to create a separate function file for randi() and get the user inputted k1 value into that function file. I only know how to create the random number from within these loops. I tried creating a function called randomnumber but I need a k value that only comes from the GUI input. Can somebody point me in the right direction? Any help is greatly appreciated
tally = zeros(1, 365);
N = 1000;
k1 = 365;
for k = 2:k1
for m = 1:N
rdie = randi(365, 1, k);
for i = 1:length(rdie)
b = rdie(i);
ind = find(rdie == b);
if length(ind) > 1
tally(k) = tally(k) + 1;
break
end
end
end
end
probability = tally/N;
x = 2:k1;
y = probability;
L = min(length(x), length(y));
plot(x(1:L), y(1:L))
xlabel('Number of people')
ylabel('Probability')

採用された回答

Voss
Voss 2022 年 4 月 24 日
If I understand what you want to do, you can create an m-file called get_k_random_days.m (or whatever you want to call it), with contents as follows:
function out = get_k_random_days(k)
out = randi(365,1,k);
end
And in your loop, instead of calling randi, you would call get_k_random_days:
for k = 2:k1
for m = 1:N
rdie = get_k_random_days(k);
...
...
Is that the idea?
  2 件のコメント
Katherine Sadler
Katherine Sadler 2022 年 4 月 24 日
YES. Thank you :)
Voss
Voss 2022 年 4 月 24 日
You are welcome!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeBirthdays についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by