while expression specification - problems with error messages

6 visualizzazioni (ultimi 30 giorni)
Hello,
is there any (simple) way to set up that an input can contain ONLY values from an interval (not necessarily of integers)?
Something such as:
abc=input('Choose a number from <-1000;999>: ')
while abc<1000||abc>999
abc=input('Wrong! Choose again a number from <-1000;999>: ')
works good, when I answer outside the interval. However, when I answer with a letter or with nothing typed at all - just clicking on enter button, I get these error messages:
??? Error using ==> input
Undefined function or variable '_that letter_'.
or
??? Error: Unexpected MATLAB expression.
for the letters. And:
??? Operands to the || and && operators must be convertible to logical scalar values.
Error in ==> blah at 12
while abc<-1000||abc>999
while no typing an answer at all. I want to make it idiotproof as much as possible.
I guess I am not even taking into account typing more inputs (probably nargin>1; error('... :'?). That could actually sort out the latter, too via nargin<1, right?

Risposta accettata

Walter Roberson
Walter Roberson il 31 Dic 2012
If you wish to be able to detect and smoothly handle letters in input, you need to use
abc_string = input('Choose a number from <-1000;999>: ', 's');
and then you have to figure out whether the string in abc_string looks like a number or not and then convert it to a numeric value.
Note: your current code has
while abc<1000||abc>999
but the beginning of your range is negative so you would want
while abc<-1000||abc>999

Più risposte (1)

Azzi Abdelmalek
Azzi Abdelmalek il 31 Dic 2012
Modificato: Azzi Abdelmalek il 31 Dic 2012
abc=input('Choose a number from <-1000;999>: ')
while abc<-1000 || abc>999
abc=input('Wrong! Choose again a number from <-1000;999>: ')
if isempty(abc) | ~isnumeric(abc)
abc=1000
end
end
  4 Commenti
Walter Roberson
Walter Roberson il 31 Dic 2012
You can use try/catch . But better is to use the 's' option of input() and look at whether you have a number-like-string before you convert the string to numeric.
John
John il 4 Gen 2013
Thank you, Azzi. I didn't know about isempty and isnumeric. (I thought it is possible to accept both answers)

Accedi per commentare.

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by