Unrecognized function or variable
5 views (last 30 days)
Show older comments
Stephan van Kalmthout
on 12 Feb 2020
Answered: Walter Roberson
on 12 Feb 2020
I am trying to make a centigrade to fahrenheit converter with build in check for strings and I want the program to be reset itself when a non numerical value is given as input. This is what I got so far:
val=input('Centigrade: ');
tf=isstring(val);
if tf==0
Fahrenheit=val.*9/5+32
else tf==1
disp('Your input was a string, please try again')
end
The code works for numerical values, but when I enter 'w' for example it also generates a value in fahrenheit. When I leave out the '' (just entering w) it gives me the following error:
Error using input
Unrecognized function or variable 'w'.
Error in Untitled6 (line 5)
val=input('Centigrade: ');
Anyone who can tell me what I should do and why the code isn't working properly?
Thanks in advance!
0 Comments
Accepted Answer
Walter Roberson
on 12 Feb 2020
'w' is not a string, it is a character. isstring() tests specifically for string() objects.
When you use input() without the 's' option then everything that is entered is executed with eval(). If the input includes text that does not happen to match a variable or function name then when the eval() happens you will get the error message that you saw.
I would recommend that you stop trying to test only for strings, because when you use input() the user can enter any code to return any data type.
What I recommend is that if you use input() that you use the 's' option. When you do that, the user input is not executed and is returned as a character vector (not a string object). If the user entered 1.23 at the input prompt, then '1.23' character vector would be returned, not the number 1.23. Then with the character vector in hand, use str2double. That function has the property that if the input does not represent exactly one number, then the function returns nan. Only regular number-building characters are permitted. Entering w or 1,2 would get you a nan result. And if the user did enter a single number then you get the numeric value rather than nan.
0 Comments
See Also
Categories
Find more on Characters and Strings 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!