If else problem homework
Show older comments
Hi everyone, the howework question is :
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 input is not a positive integer scalar, return false as well. Note that every year that is exactly divisible by 4 is a leap year, except for years that are exactly divisible by 100. However, years that are exactly divisible by 400 are also leap years. For example, the year 1900 was not leap year, but the year 2000 was. Note that your solution must not contain any of the date related built-in MATLAB functions.
My code as an answer to this question was:
function a = valid_date(y,m,d)
if ~isscalar(y) || ~isscalar(m)|| ~isscalar(d)
a = false;
else
if m>=1 && m<=12
if m==1||m==3||m==5||m==7||m==8||m==10||m==12
if d>=1 && d<=31
a = true;
else
a = false;
end
elseif m==4||m==6||m==9||m==11
if d>=1 && d<=30
a = true;
else
a = false;
end
else
if rem(y,4)==0 && rem(y,100)~=0
if d>=1 && d<=29
a = true;
else
a = false;
end
elseif rem(y,400)==0
if d>=1 && d<=29
a = true;
else
a = false;
end
else
if d>=1 && d<=28
a = true;
else
a = false;
end
end
end
else
a = false;
end
end
but I wonder that if there is a shorter answer (but sticking to the limitations of the question). If there is one, I'll be waiting for your answers.
Thank you !!
Accepted Answer
More Answers (0)
Categories
Find more on Time Series Objects in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!