How to stop running code once conditions are met?

26 次查看(过去 30 天)
Hey guys, I'm trying to determine the average amount of people it would take to have two peopleh have the same birthday. Essentially I'm looking at the birthday paradox as an assignment for school. I haven't added the part where the function will run multiple times just yet. I'm still trying to figure out how to stop the program once two of the same number are rolled, store how many times that took, and then repeat for a thousand iterations. I know that this is probably not the best way to go about handling the code, but I'm having a hard time figuring out how else to go about it. I was thinking about using a while loop, but I don't know what the conditional statment would be.
function F = Birthday
% Birthday Paradox
%generates
%
% Outputs:
% Number of people before two people have the same birthday
%Created on:4/6/23
%Created by: M. Bruce
%Initialization
F = zeros(1,1000);
for n = 1:1000
F(n) = randi(365);
for k = 1:n-1
if F(n) == F(n-k)
break
else
return
end
end
end

回答(2 个)

Walter Roberson
Walter Roberson 2023-4-8
found_duplicate = false;
for k = 1:n-1
if F(n) == F(n-k)
found_duplicate = true;
break
end
end
if found_duplicate
do the statistics stuff
end

James Tursa
James Tursa 2023-4-8
编辑:James Tursa 2023-4-8
If your Birthday function is supposed to represent only one trial (a reasonable thing to do), then you should be returning n, not F. And when your inner for-loop finds a match, it needs to break out of both loops, not just the inner loop. E.g.,
% Some trials
for k=1:10
Birthday
end
ans = 37
ans = 17
ans = 37
ans = 36
ans = 17
ans = 21
ans = 11
ans = 27
ans = 37
ans = 23
function n = Birthday % one trial of the birthday paradox
% Birthday Paradox
%generates
%
% Outputs:
% Number of people before two people have the same birthday
%Created on:4/6/23
%Created by: M. Bruce
%Initialization
F = zeros(1,365);
for n = 1:365
F(n) = randi(365);
for k = 1:n-1
if F(n) == F(n-k) % could simply use F(k) here instead of F(n-k)
return % done, so break out of both loops and return n
end
end
end
end
You can modify my "trials" loop to run a thousand trials, gather results, and generate statistics on these results.

类别

Help CenterFile Exchange 中查找有关 Birthdays 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by