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.

54 views (last 30 days)
Hi Folks,
I have tried and ended up in errors. For example(valid_date(2018, 4, 1) failed,The last day of every month
Variable valid has an incorrect value. valid_date(2000, 1, 31) failed..., Random leap years
Variable valid has an incorrect value. valid_date(1624, 2, 29) failed..., Random dates
Variable valid has an incorrect value. valid_date(1433, 6, 28) failed...)
Kindly point out the errors I have made!
function valid = valid_date(year,month,day)
if (nargin==3)
if (fix(valid_date)&&isscalar(valid_date))
if((rem(year,4)==0||rem(year,400)==0) && rem(year,100)~=0)
if((month==1||3||5||7||9||11) && 0<day<32)
valid=true;
elseif(month==2 && 0<day<30)
valid=true;
elseif((month==4||6||8||10||12) && 0<day<31)
valid=true;
else
valid=false;
end
else
if((month==1||3||5||7||9||11) && 0<day<32)
valid=true;
elseif((month==4||6||8||10||12) && 0<day<31)
valid=true;
elseif(month==2 && 0<day<29)
valid=true;
else
valid=false;
end
end
else
valid=false;
end
else
valid=false;
end

  3 Comments

Stephen Cobeldick
Stephen Cobeldick on 27 Jun 2019
Note that this syntax
month==1||3||5||7||9||11
is equivalent to:
(((((month==1)||3)||5)||7)||9)||11
which, because 11 is non-zero, will always be true. You should start thinking about using vectors, which would make that comparison easy (hint: use any)
Guillaume
Guillaume on 27 Jun 2019
As Stephen points out, inventing your own syntax for the if tests is not going to work very well. Note that to check if a number is a member of the set {a,b,c}, you'd use ismember(x, [a, b, c]), not some invented x==a||b||c syntax.
In this case, it didn't even matter that the comparison didn't make sense because of:
if fix(valid_date)&&isscalar(valid_date) %removed unnecessary parentheses
%...
end
which recurse into valid_date, this time with no argument. Since valid_date with 0 inputs always return false (thankfully, breaking the recursion), and since fix(false) is always false, the above if is always false.
As coded, the function can be simply reduced to
function valid = valid_date(~, ~, ~)
valid = false;
end
Rakeshwar Elango
Rakeshwar Elango on 28 Jun 2019
Thank you Stephen and Guillaume as the newly invented statement of me didn't through any error so I was wandering wheather where it went wrong. Thank you for your suggesion!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!