How to check if a user entered input will form a valid function handle?

7 次查看(过去 30 天)
The user enters a character vector (in the edit text field of Appdesigner). I want to convert it into a function handle. I am doing this by concatenating it with '@(x,y)', making the function compatible with matrices and then using str2func. However, I want to be able to check if the input by the user is valid. Also, the function entered by the user must have its variables as x and/or y only.
For example, if the entered input is 'log(x)+sin(y)' the entry is valid whereas if the input is 'log(x)+*sin(y)' it should show an error.
Thanks,
Mohit.

采纳的回答

Ameer Hamza
Ameer Hamza 2020-10-8
You may try exception handling to check if a function handle is valid
x = 'x^2+2+SUM(x)'; % SUM is not a valid function in MATLAB
f = str2func(['@(x) ' x]);
is_correct = true;
try
f(0); % or some other value
catch ME
is_correct = false;
error(ME.message); % throw an error, remove this line if you don't
% want an error appearing in command window.
end

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Argument Definitions 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by