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
Muhammad Usman Saleem 2016 年 6 月 28 日
share your code? then will get your problem
Andreas Donauer
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?
Stephen23
Stephen23 2016 年 6 月 28 日
編集済み: Stephen23 2016 年 6 月 28 日
@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.

サインインしてコメントする。

 採用された回答

Guillaume
Guillaume 2016 年 6 月 28 日

1 投票

You have several options:
1. Continue using input as is, but just wrap it in a try, catch block.
isokinput = false;
while ~isokinput
try
userinput = input('enter some numbers');
isokinput = true; %this line only gets executed if input does not raise an error
catch
fprintf('Invalid expression. Please retry\n\n');
end
end
2. Take the input as string, check that the string is valid. For example to check that only digit were entered (using regexp):
isokinput = false;
while ~isokinput
userinput = input('enter some numbers', 's');
if isempty(regexp(userinput, '^\d+$')) %check that only digits have been entered
fprintf('Invalid expression. Please retry\n\n');
else
isokinput = true;
end
end
3. Again, take the input as string. Attempt to convert it to number and complain if it doesn't:
isokinput = false;
while ~isokinput
userinput = input('enter some numbers', 's');
usernumber = str2double(userinput); %will return nan if it can't convert the number
if isnan(usernumber)
fprintf('Invalid expression. Please retry\n\n');
else
isokinput = true;
end
end

1 件のコメント

mtmtmt
mtmtmt 2016 年 6 月 28 日
Thank you so much! I have implented option three, it works perfectly:)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

質問済み:

2016 年 6 月 28 日

編集済み:

2016 年 6 月 28 日

Community Treasure Hunt

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

Start Hunting!

Translated by