Effacer les filtres
Effacer les filtres

Unrecognized function or variable

7 vues (au cours des 30 derniers jours)
Stephan van Kalmthout
Stephan van Kalmthout le 12 Fév 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!

Réponse acceptée

Walter Roberson
Walter Roberson le 12 Fév 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.

Plus de réponses (1)

Bhaskar R
Bhaskar R le 12 Fév 2020
Modifié(e) : Bhaskar R le 12 Fév 2020
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.

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Produits


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by