Input is a valid integer

조회 수: 12 (최근 30일)
Pavithra Naidu
Pavithra Naidu 2015년 10월 29일
편집: DGM 2024년 5월 31일
How to check if the value entered by the user is a valid integer and not a negative number(such as -1,-9,-10 etc) or characters/strings(such as a, i,thank you)or special symbols(such as @,* etc) and also that is not equal to 0?

답변 (2개)

Walter Roberson
Walter Roberson 2015년 10월 29일
https://www.mathworks.com/matlabcentral/newsreader/view_thread/163080
  댓글 수: 1
omri dagan
omri dagan 2024년 5월 30일
it's a broken link

댓글을 달려면 로그인하십시오.


DGM
DGM 2024년 5월 31일
편집: DGM 2024년 5월 31일
Assuming the input x is a char vector from input() which represents a numeric scalar:
isvalidnumber('56') % positive scalar integer is okay
ans = logical
1
isvalidnumber('-56') % not valid (not positive)
ans = logical
0
isvalidnumber('56.2') % not valid (noninteger)
ans = logical
0
isvalidnumber('[56 23]') % not valid (nonscalar)
ans = logical
0
isvalidnumber('asdf') % not valid (non-numeric)
ans = logical
0
isvalidnumber('56E3') % E-notation is valid (56000 is a positive scalar integer)
ans = logical
1
function isvalid = isvalidnumber(x)
x = str2double(x); % NaN if text or nonscalar numeric
isvalid = (x > 0) & (mod(x,1) == 0); % true only for positive integers
end
There are probably other ways to approach this, but it's a basic start. If you really want to improve things, take a step back and stop designing around accumulating parameters interactively via input().

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by