Verifying user input
Show older comments
Hi there,
How can you verify numerical input from a user. I have this little program here, and it works fine until the user enters a non numerical input. How do you get matlab to check if it is a number or character?
Thanks in advance
Accepted Answer
More Answers (2)
Jan
on 23 Feb 2011
A simple test is letting SSCANF count the number of accepted characters:
s = '0.12345'
sFull = deblank(s);
[num, count, errmsg, nextIndex] = sscanf(sFull, '%g', 1);
if nextIndex == length(sFull + 1) && count == 1
fprintf('This is a scalar number: %s\n', sFull)
else
fprintf(2, 'This is not a scalar number: %s\n', sFull)
end
Robert Cumming
on 23 Feb 2011
0 votes
Check what the user inputs using something like:
isnumeric
see help isnumeric to get a list of similar checks you can perform
3 Comments
Jan
on 23 Feb 2011
I'm sure, Robert means the contents of a string input, while ISNUMERIC checks the type of a variable.
Robert Cumming
on 23 Feb 2011
well spotted! ;)
Indeed it depends on what he is doing with the user input, if he is converting the string input to a number he could check if that was valid using isempty
OLUBUKOLA ogunsola
on 14 Jun 2016
this post is old, i hope someone reads this . what if i want to check if input is numeric and the 26 alphabets, nothing else is allowed . how can i do this
Categories
Find more on Cell Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!