19

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

eykanal
  • 26,437
  • 19
  • 82
  • 113
tirth
  • 813
  • 1
  • 8
  • 16
  • See also [this question](http://stackoverflow.com/q/19307726/2778484), which test for validity (having code to back it) as well as being a function handle. – chappjc Jul 24 '14 at 16:46

2 Answers2

32

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.

Egon
  • 4,757
  • 1
  • 23
  • 38
4

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

Max
  • 2,121
  • 3
  • 16
  • 20