checking input an integer greater than 0?

33 ビュー (過去 30 日間)
Jens Petit-jean
Jens Petit-jean 2020 年 11 月 16 日
コメント済み: John D'Errico 2020 年 11 月 17 日
how can I check if my input is a integer greater than 0?

回答 (3 件)

John D'Errico
John D'Errico 2020 年 11 月 16 日
編集済み: John D'Errico 2020 年 11 月 16 日
If you want to check for an integer that exceeds zero, first use the && and || operators.
So assuming you want to throw an error if it fails, then I might do...
if (x <= 0) || (rem(x,1) ~= 0)
error('Oh nO, Mr. Bill! x was not a positive integer.')
end
You use the || operator here, because MATLAB is more efficient with them in an if statement. They short circuit the test, so if the first part of the test is true, then there is no need to even execute the second clause in the test. The && operator works the same way.
I might even have added a test that x be a scalar variable.
If your question is you want to do something specifically if x is a positve integer, then another ay to write it would be:
if (numel(x) == 1) && (x > 0) && (fix(x,1) == 0)
disp('Happy days are here again...')
else
error('Oh nO, Mr. Bill! x was not a scalar positive integer.')
end
As you can see, I even added a test that x be scalar. There are of course alternative ways to test for an element being an integer. (fix(x)==x) is another, or (round(x) == x). Note that all such tests, when applied to a scalar are all extremely fast. Actually, the slowest of them is the rem test I used above.
You should also see that when I changed the if statement, I now had to use &&, which is the short-circuited version that applies.
  2 件のコメント
James Tursa
James Tursa 2020 年 11 月 16 日
Your first suggestion covers the x==inf case, but the second formulation doesn't.
John D'Errico
John D'Errico 2020 年 11 月 17 日
Good point. Best of course would be to explicitly test for inf or NaN input.

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


Ameer Hamza
Ameer Hamza 2020 年 11 月 16 日
編集済み: Ameer Hamza 2020 年 11 月 16 日
You can use this condition
tf = (x>0) & (round(x)==x)
Example
>> x = 5;
>> tf = (x>0) & (round(x)==x)
tf =
logical
1
>> x = 4.5;
>> tf = (x>0) & (round(x)==x)
tf =
logical
0
  3 件のコメント
Ameer Hamza
Ameer Hamza 2020 年 11 月 16 日
Can you give an example of how it does work?
James Tursa
James Tursa 2020 年 11 月 16 日
Doesn't cover the x==inf case.

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


Matt J
Matt J 2020 年 11 月 16 日
編集済み: Matt J 2020 年 11 月 16 日
validateattributes(yourInput,"numeric",{"integer","nonnegative"})
  1 件のコメント
John D'Errico
John D'Errico 2020 年 11 月 16 日
"greater than 0"
validateattributes(yourInput,"numeric",{"integer","positive"})

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

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by