Unrecognized function or variable

조회 수: 17 (최근 30일)
Stephan van Kalmthout
Stephan van Kalmthout 2020년 2월 12일
답변: Walter Roberson 2020년 2월 12일
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