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.
  댓글 수: 2
Ameer Hamza
Ameer Hamza 2020년 10월 8일
Why 'log(x)+-sin(y)' is invalid? It is a valid MATLAB syntax.
Mohit Kumar
Mohit Kumar 2020년 10월 8일
Okay, that was a poor mistake on my part. Something like log(x)+*sin(y). Have made the same change in the question.

댓글을 달려면 로그인하십시오.

채택된 답변

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
  댓글 수: 2
Mohit Kumar
Mohit Kumar 2020년 10월 8일
Thanks! Seems to be working great as far I tested.
Ameer Hamza
Ameer Hamza 2020년 10월 8일
I am glad to be of help! Let me know in the comment if there is some edge case where it fails.

댓글을 달려면 로그인하십시오.

추가 답변 (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