How can I create a function that gives me logical true or logical false for a certain date?

I've been doing a Coursera course for MatLab and I'm stuck in this task that ask me for this function. Debugger have helped but I'm not been able to find any more mistakes
This is my code so far:
function [valid] = valid_date(year, month, day)
%rule for non scalar inputs
if ~isscalar(year) == true || ~isscalar(month) == true || ~isscalar(day) == true
valid = false;
else
valid = true;
return
end
%rule for other months
M31 = [1 3 5 7 8 10 12];
if ismember(day, 1:31) == 1
elseif ismember(month, M31)
valid = true;
else
valid = false;
end
if ismember(day, 1:30) == 1
M30 = [4 6 9 11]
elseif ismember(month, M30)
valid = true;
else
valid = false;
return
end
%rule for february
if month == 2
elseif ismember(day, 1:28) == 1
valid = true;
else
valid = false;
end
%rule for non-leap years
if month == 2 && day == 29
elseif mod(year, 4) ~= 0
end
valid = false;
%rule for leap years
if mod(year, 400) == 0
valid = true;
elseif mod(year, 100) == 0
valid = false;
elseif mod(year, 4) == 0
valid = true;
else
valid = false;
end
end

3 Comments

Vinicius - this first block seems a little overly complex
if ~isscalar(year) == true || ~isscalar(month) == true || ~isscalar(day) == true
valid = false;
else
valid = true;
return
end
If you are exiting the function early then valid should be false. I think that you could instead have
valid = true;
if ~isscalar(year) || ~isscalar(month) || ~isscalar(day)
valid = false;
return;
end
As for any other bugs, are there specific inputs that return an invalid response?
Yes, dates of random non-leap years like (1995, 2, 29) and random dates like (223, 12, 32).
I recommend that you put a breakpoint in your code and use the MATLAB debugger to step through each line. See what happens to valid when the year is 1995, the month is 2, and the day is 29. If your above code is not returning the correct response (false), then there must be some line that is setting valid to true...the debugger should help you determine that.

Sign in to comment.

Answers (1)

if ~isscalar(year) == true || ~isscalar(month) == true || ~isscalar(day) == true
valid = false;
else
valid = true;
return
end
If any of year, month, or day are not scalar, then you set valid = false but you continue execution even though it is not possible for the date to be later determined to be valid under those circumstances.
If all of year, month, and day are scalar, then you set valid = true and return without having processed any of the other tests, so you would for example declare that year -17 month 42 day 3.8 is acceptable input.

1 Comment

Should I create a general rule, for example, using the fix, ceil, floor or round functions, to exclude those imputs?

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!