MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

You call a function using a handle the same way you call the function directly. For
example, suppose that you have a function named computeSquare, defined as:


function y = computeSquare(x)
y = x.^2;
end


Create a handle and call the function to compute the square of four.


f = @computeSquare;
a = 4;
b = f(a)


b =


16


If the function does not require any inputs, then you can call the function with empty
parentheses, such as


h = @ones;
a = h()


a =


1


Without the parentheses, the assignment creates another function handle.


a = h


a =


@ones


Function handles are variables that you can pass to other functions. For example,
calculate the integral of x^2 on the range [0,1].


q = integral(f,0,1);


Function handles store their absolute path, so when you have a valid handle, you can
invoke the function from any location. You do not have to specify the path to the function
when creating the handle, only the function name.


Keep the following in mind when creating handles to functions:


Create Function Handle
Free download pdf