Check if a function handle is valid
15 views (last 30 days)
Show older comments
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 Comment
Steven Lord
on 26 Feb 2021
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"?
Accepted Answer
Kurt Schmutz
on 18 Sep 2014
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 Comments
More Answers (3)
Sean de Wolski
on 1 Jul 2014
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.
0 Comments
Ryan
on 1 Jul 2014
1 Comment
Sean de Wolski
on 1 Jul 2014
Well if you catch the MException, you could look at the message of it.
...
catch ME
ME.message
end
See Also
Categories
Find more on Performance and Memory in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!