Anonymous functions can be defined anywhere inside a script.
They are created using the following
syntax:
myfunc=@(inputVars) expression
Anonymous functions can be used like any other
functions.
resultant=@(x,y) sqrt(x^2+y^2)
resultant(5,12) => 13
However, the values of any local variables used by the anonymous function are copied at the
time the function is defined, as shown
below:
b=1
silly=@(x) x+b
b=2
silly(9)
returns a value of 10, not 11.
Local variables used by an anonymous function cannot be defined later. If they do not exist
at the time the function is defined, an error will occur when the function is used.
Anonymous functions also provide a means of passing additional parameters to a function
that is to be used as an argument. Consider the following
scenario:
function result = ObjFunc(p, data)
...
end
init = [5,3]
data = [2,3,5,7];
[x,fval] = fminunc(@ObjFunc, init)
Passing
ObjFunc to
fminunc will not work because
fminunc expects
ObjFunc to have one argument. The
solution is to use an anonymous function, like
this:
[x,fval] = fminunc(@(x) ObjFunc(x, data), init)
The anonymous function satisfies the requirement of having one argument
(
x), and allows the second argument (
data) to be
passed to
ObjFunc. This can also be accomplished using a function handle
for the anonymous function, as
follows:
handle = @(x) ObjFunc(x, data)
[x,fval] = fminunc(handle, init)