Question: In Matlab, how can I check if a function handle is a particular function or function type?
Example: Let f1
be a function handle. How do I check if f1
is the in-built Matlab function mean
? How do I check if f1
is an anonymous function?
My Current Solution: My current solution to this problem involves a call to the functions
function. functions
accepts a function handle as input and returns a structure containing information about the input function handle, eg function type, path, function name etc. It works, but it is not an ideal solution because, to quote the official documentation:
"Caution MATLAB® provides the functions
function for querying and debugging purposes only. Because its behavior may change in subsequent releases, you should not rely upon it for programming purposes."
How about using func2str?
If this is an inbuilt function, it should just return a string containing the function name; if it is an anonymous function it should return the anonymous function (including @).
h1 = @(x) x.^2;
h2 = @mean;
str1 = func2str(h1); %str1 = "@(x) x.^2"
str2 = func2str(h2); %str2 = "mean"
You can also use isequal to compare two function handles (ETA: this will not work to compare two anonymous functions unless one was created as a copy of the other):
isequal(h1,@mean); % returns 0
isequal(h2,@mean); % returns 1