Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab - Check if function handle is a particular function or function type

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."

like image 712
Colin T Bowers Avatar asked Aug 12 '13 09:08

Colin T Bowers


People also ask

How do you check a function handle in MATLAB?

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.

What is the function handle in MATLAB?

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).

How do you compare functions in MATLAB?

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.

Is type a function in MATLAB?

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.


1 Answers

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
like image 144
nkjt Avatar answered Sep 19 '22 10:09

nkjt