If else problem homework

1 view (last 30 days)
Berk Öztürk
Berk Öztürk on 18 Dec 2022
Commented: Berk Öztürk on 19 Dec 2022
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

Image Analyst
Image Analyst on 18 Dec 2022
Requirement say "The name of the output argument is valid." but you have
function a = valid_date(y,m,d)
instead of
function valid = valid_date(y,m,d)
Also, your function does not always return a value should there be some error thrown. That's why it's best to set a default immediately upon entering the function, not buried inside if blocks. A bonus of doing that is you can avoid lots of else blocks
function valid = valid_date(y,m,d)
valid = false;
if ~isscalar(y) || ~isscalar(m)|| ~isscalar(d)
return;
end
% Make 2 digit years in the 2000's
if y < 1000
y = y + 2000;
end
% Check by month.
if m >= 1 && m <= 12
if m==1||m==3||m==5||m==7||m==8||m==10||m==12
% January, March, May, July, August, October, December.
if d>=1 && d<=31
valid = true;
end
elseif m==4||m==6||m==9||m==11
% April, June, September, November
if d>=1 && d<=30
valid = true;
end
else
% February. Check leap year rules.
if rem(y,4)==0 && rem(y,100)~=0
if d>=1 && d<=29
valid = true;
end
elseif rem(y,400)==0
if d>=1 && d<=29
valid = true;
end
else
if d>=1 && d<=28
valid = true;
end
end
end
end
end
  1 Comment
Berk Öztürk
Berk Öztürk on 19 Dec 2022
thank you for your answer, it helped a lot.

Sign in to comment.

More Answers (0)

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!