Creating functions to use inside for loops - birthday paradox simulation
4 views (last 30 days)
Show older comments
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')
0 Comments
Accepted Answer
Voss
on 24 Apr 2022
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?
More Answers (0)
See Also
Categories
Find more on Birthdays 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!