Why is the Matches variable too large?
Mostrar comentarios más antiguos
I was playing around with a code that produces a simulator for the birthday paradox. Here's the piece of code:
ready = false;
while ~ ready
% User inputs and defining variables
birthday_repeats = input('select the number of birthday repeats from 10-500:');
if birthday_repeats > 500 || birthday_repeats < 10 || isempty(birthday_repeats) || round(birthday_repeats) ~= birthday_repeats|| isnan(birthday_repeats)
disp('error')
continue
end
sample_size = input('Select the sample size from 2-365: ');
if sample_size > 365 || sample_size < 2|| isempty(sample_size) || round(sample_size) ~= sample_size || isnan(sample_size)
disp('error')
continue
end
matches = zeros(1,sample_size);
N = 1000;
days = randi(1,365);
% simulation run
for k = 1:birthday_repeats % desired number of trials
matches = 0;
for j = 1:days
if test(days)
matches(sample_size) = matches(sample_size) + 1;
end
end
match_tally = matches(sample_size)/N;
end
I'm not sure why after each iteration of the loop the variable 'matches(sample_size)' is too large and here's the the 'test' function:
function out = test(data)
out = false;
n = length(data);
for k = 1:n
for i = k+1:n
if data(k) == data(i)
out = true;
break
end
end
end
end
Respuesta aceptada
Más respuestas (1)
Walter Roberson
el 2 de Mayo de 2023
days = randi(1,365);
That does not request a random number between 1 and 365. That requests 365 x 365 random numbers in the range 1 to 1.
2 comentarios
Walter Roberson
el 2 de Mayo de 2023
Yes, you can see from the summary output
days = 1x365
that it has generated a 1 x 365 array.
Note that many elements in days will be repeated. If you need to have a random permutation of the day numbers, use randperm
Categorías
Más información sobre Birthdays en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
