Example 2 — Constructing a Handle to an Anonymous Function
The statement below creates an anonymous function that finds the square of a number. When you call this function, MATLAB assigns the value you pass in to variable x, and then uses x in the equation x.^2:
sqr = @(x) x.^2;
The @ operator constructs a function handle for this function, and assigns the handle to the output variable sqr. As with any function handle, you execute the function associated with it by specifying the variable that contains the handle, followed by a comma-separated argument list in parentheses. The syntax is
fhandle(arg1, arg2, ..., argN)
To execute the sqr function defined above, type
a = sqr(5)
a =
25
Because sqr is a function handle, you can pass it in an argument list to other functions. The code shown here passes the sqr anonymous function to the MATLAB integral function to compute its integral from zero to one:
integral(sqr, 0, 1)
ans =
0.3333