All of those if-elseif blocks make the code difficult to read, and difficult to debug as well. I would advise against that approach, and instead tackle each issue one at a time and code only for that issue. That makes the logic of each test much easier to read and to debug. For example, here is an outline of what the code could do using words:
function valid = valid_date(year,month,day)
valid = false;
if( the year is not a positive integer scalar )
return;
end
if( the month is not a positive integer scalar )
return;
end
if( the day is not a positive integer scalar )
return;
end
if( the month is not between 1 and 12 inclusive )
return;
end
days_in_month = a 12-element array of the number of days in each month;
is_leap_year = (you put some code here to determine if the year is a leap year)
if( is_leap_year )
Change the days_in_month value for February to 29
end
if( the day is greater than the number of days in the month )
return;
end
valid = true;
return;
end
Once you are satisfied that the words do what you want (you should check this yourself ... maybe I missed something that needs to be checked), then you need to write actual code for all of the worded places. The code you write for this outline will in many places be pieces of the code you have already written in your if-elseif blocks above.
Best Answer