2.11 Anonymous Functions, y = @(x) x^2
The main use for anonymous functions Links to an external site. is to create short simple functions without the overhead of writing complete m-files. The function consists of variables listed in @(...) followed by an expression to be evaluated when the function is called.
The expression can include other variables but these are fixed when the function is created, as illustrated in the example below.
a=2; %Define a variable
fnc = @(x) a*x.^2; %and an anonymous function using the variable
fnc([1 3 4 7]) %Calling the function replaces x with the argument, [1 3 4 7]
a=4; %Note that a is fixed when constructing the function,
fnc([1 3 4 7]) %and changing it afterwards has no effect.
fnc = @(x,a) a*x.^2; %We could have defined the function using two arguments
fnc([1 3 4 7], 2) %allowing us to change the value of a
fnc([1 3 4 7], 4) %when calling the function
Anonymous function exist in most programming languages, in python and c/c++ they are called lambda-expressions.
/Johan Lindström