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."
MATLAB® considers function handles that you construct from the same named function to be equal. The isequal function returns a value of true when comparing these types of handles. If you save these handles to a MAT-file, and then load them back into the workspace, they are still equal.
A function handle is a MATLAB® data type that stores an association to a function. Indirectly calling a function enables you to invoke the function regardless of where you call it from. Typical uses of function handles include: Passing a function to another function (often called function functions).
You can compare character vectors and cell arrays of character vectors to each other. Use the strcmp function to compare two character vectors, or strncmp to compare the first N characters. You also can use strcmpi and strncmpi for case-insensitive comparisons. Compare two character vectors with the strcmp function.
The type function checks the directories specified in the MATLAB search path, which makes it convenient for listing the contents of M-files on the screen. Use type with more on to see the listing one screenful at a time. type filename is the unquoted form of the syntax.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With