MATLAB Answers

How do I check that input is numerical?

322 views (last 30 days)
Seán Ó Héir
Seán Ó Héir on 24 Apr 2017
Edited: Adam on 24 Apr 2017
I'm trying to create a program that will prompt the user for a numerical input, for example: 'What age are you?'. I know how to prompt the user to ask for an input, but I want to know how to check the answer to make sure it is a numerical figure, ie to stop the user putting in the answer 'twelve'. Any help would be greatly appreciated.
Seán
  1 Comment
Stephen
Stephen on 24 Apr 2017
More reliable than str2num is to use str2double (which does not call eval and does not evaluate arbitrary code). str2double outputs NaN for invalid input strings, so simply do this:
val = str2double(input('What age are you?','s'));
if isnan(val)
... not a number
else
... was number
end
See KSSV's answer for another example of using str2double.

Sign in to comment.

Accepted Answer

Adam
Adam on 24 Apr 2017
Edited: Adam on 24 Apr 2017
str2num( inputVal )
will return the number if it is valid or empty otherwise so a
if ~isempty( str2num( inputVal ) )
test would check it is a number, or remove the ~ if you want to check for not a number and give an error message in that case.
  2 Comments
Adam
Adam on 24 Apr 2017
Yeah, sorry, it was a quick answer and I chose a very bad variable name. I've edited it now. the argument to str2num was just meant to be your variable that you have extracted from the prompt, not a call to the 'input' function.

Sign in to comment.

More Answers (1)

Tags

No tags entered yet.

Community Treasure Hunt

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

Start Hunting!

Translated by