# why I get error in scalar portion?

1 回表示 (過去 30 日間)
SIDDHARTHKUMAR SANGHANI 2021 年 11 月 3 日

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

サインインしてコメントする。

### カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

### Community Treasure Hunt

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

Start Hunting!

Translated by