MATLAB Answers

Write a function called valid_date that takes three positive integer scalar inputs year, month, day. If these three represent a valid date, return a logical true, otherwise false. The name of the output argument is valid. If any of the inputs is not

126 views (last 30 days)
Ajith Thomas
Ajith Thomas on 29 Jun 2019
Edited: Stephen Cobeldick on 29 Jun 2019
unction valid=valid_date(year,month,date)
if nargin==3
valid1=true;
else valid=false;
return
end
v1=[year]; v2=[month]; v3=[date];
if isscalar(v1)==true && isscalar(v2)==true && isscalar(v3)==true
valid2=true;
else valid=false;
return
end
if year>0 && 0<month && month<=12 && 0<date && date<=31
valid3=true;
else valid=false;
return
end
a=year/4; b=year/100; c=year/400;
if rem(year,4)==0 && rem(year,100)~=0
valid4=true;
else valid4=false;
end
if rem(year,100)==0 && rem(year,400)~=0
valid5=true;
else valid5=false;
end
if rem(year,400)==0
valid4=true;
else valid4=false;
end
if (month==1||3||5||7||8||10||12 && date<=31) || (month==2 && date<=29) || (month==4||6||9||11 && date<=30) && valid4==true && valid5==false
valid6=true;
else valid6=false;
end
if (month==1||3||5||7||8||10||12 && date<=31) || (month==2 && date<=28) || (month==4||6||9||11 && date<=30) && valid5==true && valid4==false
valid7=true;
else valid7=false;
end
if valid1==true && valid2==true && valid3==true && valid6==true
valid=true;
elseif valid1==true &&valid2==true && valid3==true && valid7==true
valid=true;
else
valid=false;
return
end
why this code is not working for 2018/4/31 and 2003/2/29? and other random dates. but is works for non scalar and random leap years

Answers (0)

Sign in to answer this question.