Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to test a variable is a function handle or not in Matlab

How to test/validate a variable is a function handle in matlab ?

it may be something like:

f=@(x)x+1
isFunctionHandle(f)

the is* build-in functions seems not support these kind testing? anyone know? many thanks

like image 486
tirth Avatar asked Oct 23 '11 15:10

tirth


People also ask

Is function handle MATLAB?

A function handle is a MATLAB® data type that represents a function. A typical use of function handles is to pass a function to another function. For example, you can use function handles as input arguments to functions that evaluate mathematical expressions over a range of values.

How do you check if a function is valid or not?

Determining whether a relation is a function on a graph is relatively easy by using the vertical line test. If a vertical line crosses the relation on the graph only once in all locations, the relation is a function. However, if a vertical line crosses the relation more than once, the relation is not a function.

How do you check variables in MATLAB?

Command Window — To view the value of a variable in the Command Window, type the variable name. For the example, to see the value of a variable n , type n and press Enter. The Command Window displays the variable name and its value. To view all the variables in the current workspace, call the who function.


2 Answers

The right way is indeed by means of an is* function, namely isa:

if isa(f, 'function_handle')
    % f is a handle
else
    % f is not a handle
end

edit: For completeness, I'd like to point out that using class() works for checking if something is a function handle. However, unlike isa, this doesn't generalize well to other aspects of MATLAB such as object-oriented programming (OOP) that are having an increasing impact on how MATLAB works (e.g. the plot functionality, the control toolbox, the identification toolbox, ... are heavily based on OOP).

For people familiar with OOP: isa also checks the super types (parent types) of the x object for someClass, while strcmp(class(x), 'someClass') obviously only checks for the exact type.

For people who don't know OOP: I recommend to use isa(x, 'someClass') instead of strcmp(class(x), 'someClass') as that is the most convenient (and commonly useful) behavior of the two.

like image 167
Egon Avatar answered Oct 16 '22 10:10

Egon


You can use the class() function:

f = @(x)x+1

f = 

    @(x)x+1

>> class(f)

ans =

function_handle

(This is a string containing the text 'function_handle')

like image 22
Max Avatar answered Oct 16 '22 09:10

Max