Clear Filters
Clear Filters

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

1 view (last 30 days)
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
Geoff Hayes
Geoff Hayes on 30 Jan 2020
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)

Walter Roberson
Walter Roberson on 30 Jan 2020
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.

Categories

Find more on Programming in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!