why I get error in scalar portion?

조회 수: 1 (최근 30일)
SIDDHARTHKUMAR SANGHANI
SIDDHARTHKUMAR SANGHANI 2021년 11월 3일
답변: Prateek Rai 2021년 11월 6일
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에서 Programming에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by