Trying to create a random date using randi and if-elseif-else statements

14 views (last 30 days)
I'm currently attempting to write code that can generate a random date. However I am running into issues while writing a conditional statement to ensure that the correct amount of days are in each month. (To ensure I dont get the 31st of Feb as an answer for example.) This is what I have so far, later I wish to generate a day and then assign the month and day into a 1x2 matrix. This always gives me "days = 31" no matter what. I also want to mention that I desire to use a conditional statement for this.
function dates = dategen(N)
month = 0;
days = 0;
month = randi(12)
if month == 1 || 3 || 5 || 7 || 8 || 10 || 12
days = 31
elseif month == 4 || 6 || 9 || 11
days = 30
else
days = 28
end

Answers (2)

KSSV
KSSV on 8 Apr 2022
theday = randi(31) ; % random day out of 31 days
themonth = randi(12) ; % random month out of 12 months
theyears = 1980:2022 ; % give the list of years you want
theyear = theyears(randperm(length(theyears),1)) ; % pick random year
thedate = datetime(theyear,themonth,theday)
thedate = datetime
01-Oct-1989
Or other option is generate all the dates and pick from it randomly.
thedates = (datetime(1980,1,1):days(1):datetime(2022,4,8))' ;
thedate = thedates(randperm(length(thedates),1))
thedate = datetime
18-Oct-1985

Voss
Voss on 8 Apr 2022
Edited: Voss on 8 Apr 2022
To understand why your code gives you days = 31 every time, consider the following:
% Case 1: seems to work ok
month = 1;
if month == 1 || 3
disp('month is 1 or 3')
else
disp('month is not 1 and not 3')
end
month is 1 or 3
% Case 2: apparently wrong
month = 2;
if month == 1 || 3
disp('(month is 1) or (3)')
else
disp('(month is not 1) and (not 3)')
end
(month is 1) or (3)
% Case 3: correct
month = 2;
if month == 1 || month == 3
disp('(month is 1) or (month is 3)')
else
disp('(month is not 1) and (month is not 3)')
end
(month is not 1) and (month is not 3)
  5 Comments
Voss
Voss on 8 Apr 2022
output = dategen(3)
output = 3×2
1 6 23 2 20 9
function dates = dategen(N)
% initialize Nx2 matrix of zeros:
dates = zeros(N,2);
% loop N times:
for ii = 1:N
month = randi(12);
if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12
day = randi(31);
date = [day, month];
elseif month == 4 || month == 6 || month == 9 || month == 11
day = randi(30);
date = [day, month];
else
day = randi(28);
date = [day, month];
end
% set the ii-th row of the output dates to be
% the day and month just generated:
dates(ii,:) = date;
end
end

Sign in to comment.

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!