why I get error in scalar portion?
2 次查看(过去 30 天)
显示 更早的评论
function valid = valid_date(year, month, day)
if nargin <3 && nargin > 3 && year < 1 && month < 1 && month > 13 && ~(isscalar(year) && isscalar(month) && isscalar(day))
valid = false;
else
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && day < 32 && day > 0
valid = true;
elseif (month == 4 || month == 6 || month == 9 || month == 11 ) && day < 31 && day > 0
valid = true;
elseif month == 2 && day < 29 && day > 0
valid = true;
elseif ((mod(year,4) == 0 && ~mod(year, 100) == 0) || (mod(year,4) == 0 && mod(year, 400) == 0)) && month == 2 && day == 29
valid = true;
else
valid = false;
end
end
end
2 个评论
Steven Lord
2021-11-3
Please show how you're calling valid_date and the full and exact text of the error message you receive (all the text displayed in red in the Command Window.)
In addition please pass along to your professor my suggestion to choose a different problem to assign as homework in the future, as this question has been asked about and discussed on MATLAB Answers a few (hundred) times before.
the cyclist
2021-11-3
I don't know if it is the source of your error, but you might want to double-check this part of your code ...
if nargin <3 && nargin > 3 ...
回答(1 个)
Prateek Rai
2021-11-6
Hi,
You should first check for the scalar portion and then for other conditions.
Additionaly, you should also check for:
if nargin <3 && nargin > 3 && year < 1 && month < 1 && month > 13
It will only be true when all the conditions satisfy at the same time. It should be something like:
if nargin <3 || nargin > 3 || year < 1 || month < 1 || month > 13
So the whole code would be:
function valid = valid_date1(year, month, day)
if ~(isscalar(year) && isscalar(month) && isscalar(day)) || nargin <3 || nargin > 3 || year < 1 || month < 1 || month > 13
valid = false;
else
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && day < 32 && day > 0
valid = true;
elseif (month == 4 || month == 6 || month == 9 || month == 11 ) && day < 31 && day > 0
valid = true;
elseif month == 2 && day < 29 && day > 0
valid = true;
elseif ((mod(year,4) == 0 && ~mod(year, 100) == 0) || (mod(year,4) == 0 && mod(year, 400) == 0)) && month == 2 && day == 29
valid = true;
else
valid = false;
end
end
end
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!