MATLAB Answers

How to write a function to determine if the inputed date is valid.Whats wrong with my valid_date function?

1 view (last 30 days)
anika kader
anika kader on 11 May 2020
Commented: anika kader on 13 May 2020
function valid = valid_date(year,month,day)
if isscalar(year)==true && year>0 && isscalar(month)==true && month>0 && 12>=month && isscalar(day)==true && day>0 %checks if input is correct
if (mod(year,4) == 0 && mod(year, 100)~= 0 || mod(year,400)==0) %checks if it's leap
isleap=true;
else
isleap=false;
end
if( any(month == [4,6,9,11]) && day<=30 )
valid = true;
if ( any(month == [1,3,5,7,8,10,12]) && day<=31)
valid = true;
else
valid=false;
end
end
elseif isleap == true && month == 2 && day<=29 || isleap == false && month ==2 && day<=28
valid=true;
else
valid=false;
end
else
valid=false;
end
end

  0 Comments

Sign in to comment.

Answers (1)

James Tursa
James Tursa on 11 May 2020
Edited: James Tursa on 11 May 2020
Consider these lines:
if( any(month == [4,6,9,11]) && day<=30 ) % <-- if you pass this test
valid = true;
if ( any(month == [1,3,5,7,8,10,12]) && day<=31) % <-- then how could you ever pass this test
That is, if the month is one of [4,6,9,11] and you passed that first if-test, then how can you ever pass that 2nd if-test which is inside the if-block of the first test? (You can't)
You need to rethink and rework this logic. Step through it one line at a time to see what it is really doing with those incorrect results.

  4 Comments

Show 1 older comment
James Tursa
James Tursa on 12 May 2020
Do you know how to use the debugger? Bring your code up in the editor, then click on a line number, e.g. near the start. When you run your code, it will pause at the line number. Then you can click one of the buttons at the top to step through your code one line at a time. Do this for one of your failed results and then you can see what the code is acutally doing so you can see the flaws in the logic.

Sign in to comment.


Translated by