Using the command "eval"

18 Ansichten (letzte 30 Tage)
Khalid Alsinan
Khalid Alsinan am 10 Dez. 2020
Kommentiert: Image Analyst am 10 Dez. 2020
I want to use the command eval, but I want my program to display an error message like: "Please try again" if the eval command doesn't work.
For example, if the user inputs:
eval('2^3')
then it's all good and the answer should be 8.
But if the user inputs:
eval('dg@^4')
then MATLAB displays: "Please try again"
  2 Kommentare
Rik
Rik am 10 Dez. 2020
Why do you want to do this in the first place?
Image Analyst
Image Analyst am 10 Dez. 2020
What do you want it to say instead, when the user enters some illegal input?
See Adam's Answer below for some more graceful ways to authenticate user input.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Adam Danz
Adam Danz am 10 Dez. 2020
Bearbeitet: Adam Danz am 10 Dez. 2020
Don't use eval() at all.
If the user should enter an expression and you want to test that the expression is functional,
responseOK = false;
while ~responseOK
try
response = input('Enter an expression (example: 2^3): '); % without quotes
if isnumeric(response)
responseOK = true;
else
fprintf('The result must be numeric.\n')
end
catch ME
fprintf('Please try again\n')
% you could use the MException (ME) to provide
% additional feedback on the error
end
end
disp(response)
If a string (or character vector) is supplied that should be evaluated as an expression, see Karan Gill's suggestion to use str2sym or you can convert it to an anonymous function but this introduces some of the risks associated with eval().
responseOK = false;
while ~responseOK
try
response = input('Enter an expression (example: "2^3"): '); % without quotes
if ischar(response) || isstring(response)
anonFcn = str2func(['@()',char(response)]);
z = anonFcn();
responseOK = true;
else
fprintf('Please enter a string or character array.\n')
end
catch ME
fprintf('Please try again\n')
% you could use the MException (ME) to provide
% additional feedback on the error
end
end
disp(z)

Kategorien

Mehr zu Scope Variables and Generate Names finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by