Why is the Matches variable too large?
이전 댓글 표시
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
채택된 답변
추가 답변 (1개)
Walter Roberson
2023년 5월 2일
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
Walter Roberson
2023년 5월 2일
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
카테고리
도움말 센터 및 File Exchange에서 Birthdays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
