How to solve Unexpected MATLAB expression for user input
显示 更早的评论
%Binary input from user
prompt= 'Input binary data in vector form eg. [1 1 0 1]: ';
ASK_input = input(prompt);
L = length (ASK_input); % Calculate length of input binary data
Error: Unexpected MATLAB expression.
1 个评论
Jan
2017-12-14
When does the error occur? When you start the code or after typing some strange data in the input command?
回答(1 个)
Guillaume
2017-12-14
You'll get all sort of weird error messages, including Unexpected MATLAB expression if the user enters anything at your prompt that is not a valid matlab expression that resolves to something that can be assigned to a variable. For example, all will be well if the user types [1 1 0 1]. However, you'll get an error if the user types 1 1 0 1 without the brackets because
ASK_input = 1 1 0 1
is not valid matlab syntax.
I agree that the error message is not very indicative of the problem. In addition, the documentation of input states that it should reprompt whereas in the above case it does not.
You can
- accept that the user has to enter a valid matlab expression and leave your code as is.
- use try... catch to catch any problem and reprompt:
while true
try
ASK_input = input(prompt);
break; %if this line is reached the entered expression was valid, exit the while loop
catch
%something went wrong with input, display a friendly error message and loop
disp('Please use valid matlab syntax for your answer');
end
end
- or take the answer unevaluated and parse it yourself, using the 's' option of input:
ASK_input = input(prompt, 's');
%you now have to parse the answer yourself
类别
在 帮助中心 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!