MATLAB Answers

I am having problems with my homework:Write a function called valid_date that takes three positive integer scalar inputs year, month, day....

7 views (last 30 days)
Mileyka Bustamante
Mileyka Bustamante on 19 May 2020
I am trying the next code, and it run. But when i submit 'various inputs' failed, someone could help me please?
function valid = valid_date(year, month, day)
if (nargin == 3)
if((isscalar(year) && isscalar(month) && isscalar(day)) && (year==fix(year) && month==fix(month) && day==fix(day)))
if (rem(year,4)==0 && rem(year,100)~=0) || (rem(year,400)==0 && rem(year,100)~=0)
if (ismember(month,[1,3,5,7,8,10,12]) && ismember(day,[1:31]))
valid=true;
elseif ismember(month,[2]) && ismember(day,[1:29])
valid=true;
elseif (ismember(month,[4,6,9,11]) && ismember(day,[1:30]))
valid=true;
else
valid=false;
end
else
if (ismember(month,[1,3,5,7,8,10,12]) && ismember(day,[1:31]))
valid=true;
elseif ismember(month,[2]) && ismember(day,[1:28])
valid=true;
elseif (ismember(month,[4,6,9,11]) && ismember(day,[1:30]))
valid=true;
else
valid=false;
end
end
else
valid=false;
end
else
valid= false;
end

  2 Comments

per isakson
per isakson on 20 May 2020
Yes, it's a bt tricky to get nested complicated if-statement right.
Are there restriction regarding use of certain Matlab functions, e.g. eomday()?
Before trying to fix the problems see: Debug a MATLAB Program

Sign in to comment.

Answers (1)

per isakson
per isakson on 20 May 2020
Replace
(rem(year,4)==0 && rem(year,100)~=0) || (rem(year,400)==0 && rem(year,100)~=0)
by
(rem(year,4)==0 && rem(year,100)~=0) || (rem(year,400)==0)
It looks like copy&paste error.
A small test
foo = @(year) (rem(year,4)==0 && rem(year,100)~=0) || (rem(year,400)==0 && rem(year,100)~=0);
>> foo(2000)
ans =
logical
0
>> foo(1900)
ans =
logical
0
>> leap = @(year) (rem(year,4)==0 && rem(year,100)~=0) || (rem(year,400)==0);
>> leap(1900)
ans =
logical
0
K>> leap(2000)
ans =
logical
1
IMO: Here is a function that is simpler to read and understand
function valid = valid_date_poi( year, month, day )
% What is worst an early return or an if-statement that spans thirty lines of code?
% I think it's ok to sometimes use early returns.
% Copyright 2020 poi
if not( nargin == 3 )
valid = false;
return % RETURN
end
is_whole_number = @(num) rem(num,1) == 0;
if not( isscalar(year) && is_whole_number(year) && year >= 0 ...
&& isscalar(month) && is_whole_number(month) && month >= 1 ...
&& isscalar(day) && is_whole_number(day) && day >= 1 )
valid = false;
return % RETURN
end
if month >= 13
valid = false;
return % RETURN
end
if day > eomday( year, month ) % Search Documentation for "leap year"
valid = false;
return % RETURN
end
valid = true;
end

  1 Comment

Mileyka Bustamante
Mileyka Bustamante on 20 May 2020
Oh thank you very much!! It was a problem with leap years! You are right, I must practice with debug function a little more!

Sign in to comment.