Write a function called valid_date that takes three positive integer scalar inputs year, month, day. If these three represent a valid date, return a logical true, otherwise false. The name of the output argument is valid.
7 views (last 30 days)
Show older comments
unction valid = valid_date(year,month,day)
if year < 1 || ~isscalar(year) || year ~= fix(year)
valid1 = false;
else
valid1 = true;
end
if month > 12 || month < 1 || ~isscalar(month) || month ~= fix(month)
valid2 = false;
else
valid2 = true;
end
if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12
if day > 31 || day < 1 || ~isscalar(day) || day ~= fix(day)
valid3 = false;
valid4 = false;
valid5 = false;
valid6 = false;
else
valid3 = true;
valid4 = false;
valid5 = false;
valid6 = false;
end
end
if month == 2
if year/4 ~= fix(year/4) || ( year/100 == fix(year/100) && year/400 ~= fix(year/400) )
if day > 28 || day < 1 || ~isscalar(day) || day ~= fix(day)
valid4 = false;
valid3 = false;
valid5 = false;
valid6 = false;
else
valid4 = true;
valid3 = false;
valid5 = false;
valid6 = false;
end
else if day > 29 || day < 1 || ~isscalar(day) || day ~= fix(day)
valid5 = false;
valid3 = false;
valid4 = false;
valid6 = false;
else
valid5 = true;
valid3 = false;
valid4 = false;
valid6 = false;
end
end
end
if month == 4 || month == 6 || month == 9 || month == 11
if day > 30 || day < 1 || ~isscalar(day) || day ~= fix(day)
valid6 = false;
valid3 = false;
valid4 = false;
valid5 = false;
else
valid6 = true;
valid3 = false;
valid4 = false;
valid5 = false;
end
end
if valid1 == true && valid2 == true && ( valid3 == true || valid4 == true || valid5 == true || valid6 == true )
valid = true;
else
valid = false;
end
end
so i know this is not the best of solutions but i tried to not get anything online and just use what i know, so it works good except for detecting non scalar inputs, so when u give it a vector or a matrix it just gives an error and doesn't give the output false and i don't know why
0 Comments
Answers (1)
Rik
on 22 Sep 2020
You test everything at once. You can do that, but you need to pay attention to what is evaluated first:
%steps in evaluation:
[3 4]<0 || ~isscalar([3 4])
[false false] || ~isscalar([3 4])
##error##
%steps in evaluation:
~isscalar([3 4]) || [3 4]<0
true || [3 4]<0
true % the second condition is not tested, because || and && and short-circuit
4 Comments
Rik
on 23 Sep 2020
For bonus rigor you can also test if you have three input arguments with nargin.
Glad to be of help. If my answer solved your problem, please consider marking it as accepted answer. If not, feel free to comment with your remaining issues.
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!