Input: How to differntiate between numbers and strings?
显示 更早的评论
Hello everyone,
I am currently writing a code that asks the user to enter a number, let's say 1, 2, or 3. However, I would like to include the case that the user accidently enters characters like 'xyz'. Matlab then displays by standard:
Error using input
Undefined function or variable 'xyz'.
What I want Matlab now to do is to just display a message like:
Invalid! Please enter 1, 2, or 3.
How can I do this?
Thanks a lot for your help!
3 个评论
Muhammad Usman Saleem
2016-6-28
share your code? then will get your problem
Andreas Donauer
2016-6-28
You will not be able to do this with the input-function. Reason is, that whatever you enter gets evaluated. Meaning, your code says:
x = input('your prompt text');
If you/user now enters 'xyz', Matlab will look for the variable xyz in your workspace - and not find it. Therefore the input crashes and the input function just repeats itself. You can not even trigger a try/catch statement, so no way to do what you ask for.
Maybe consider the function "inputdlg" instead?
@Andreas Donauer: Why is this not possible ? It works perfectly:
>> str = input('please enter a number: ','s')
please enter a number: 123
str = 123
>> str = input('please enter a number: ','s')
please enter a number: xx
str = xx
and then convert to numeric as required.
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!