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