Check if a function handle is valid

조회 수: 15 (최근 30일)
Ryan
Ryan 2014년 7월 1일
댓글: Steven Lord 2021년 2월 26일
I use str2fun(...) to create a function handle from a user-inputted string. I want to be able to run a check to make sure the function created is valid and no typos were made. I could not find a way to do this. Any suggestions?
Thanks, Ryan
MATLAB R2014a
  댓글 수: 1
Steven Lord
Steven Lord 2021년 2월 26일
What is a "valid" function handle?
f = @quit; % NOTE: Don't execute f if you have data in your MATLAB session you need!
f is a "valid" function handle in that it won't error when called. But you may not want users to enter 'quit' as the user-inputted string and blindly evaluate that function handle -- the "Bobby Tables" scenario.
g = @() zeros(1:12); % MAY error or MAY succeed and take a LONG time doing so
This may successfully execute (though it may take a while) or may throw an error depending on your computer's memory availability and your MATLAB settings. Is it "valid"?

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

채택된 답변

Kurt Schmutz
Kurt Schmutz 2014년 9월 18일
Hi Ryan
To CHECK whether a function handle is valid or not (without trial-and-error) you can do the following:
f = str2func('nameofthefunction')
fh = functions(f)
if isempty(fh.file)
% invalid :(
else
% valid :)
end
Note: file "nameofthefunction.m" must be in the current folder
Cheers, Kurt
MATLAB R2013b
  댓글 수: 4
Ryan
Ryan 2014년 9월 22일
Thanks Kurt. This worked for me since the function being used will never be anonymous.
Ryan
David Sinex
David Sinex 2021년 2월 26일
This fails if the function is a class member.

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

추가 답변 (3개)

Sean de Wolski
Sean de Wolski 2014년 7월 1일
try
fun()
catch
disp 'didn''t work'
end
Try it and catch failures. Or provide a listbox with known functions to remove the human typing element.

Ryan
Ryan 2014년 7월 1일
I thought about the try, catch method but I want to be more descriptive in the error returned. I do not know all the known functions as it is a user created function that they are using instead of a default one.
  댓글 수: 1
Sean de Wolski
Sean de Wolski 2014년 7월 1일
Well if you catch the MException, you could look at the message of it.
...
catch ME
ME.message
end

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


Jos (10584)
Jos (10584) 2014년 9월 19일
You might be interested in the function ISFUNCTION .

카테고리

Help CenterFile Exchange에서 Performance and Memory에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by