Unrecognized function or variable

17 次查看(过去 30 天)
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!

采纳的回答

Walter Roberson
Walter Roberson 2020-2-12
'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.

更多回答(1 个)

Bhaskar R
Bhaskar R 2020-2-12
编辑:Bhaskar R 2020-2-12
val=input('Centigrade: ');
When you give w MATLAB thinks as its a variable not string, if you give "w" in double quotes(not single quotes) then your program runs as desired.

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by