why I get error in scalar portion?

1 次查看(过去 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
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
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
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

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by