An anonymous function is a simple (one-line) user-defined function that is defined without creating a separate function file (M-file). Anonymous functions can be defined in the Command Window, within a script file, or inside a user-defined function.
An anonymous function is generated by typing the following command:
Where f is the function handle. The input list can contain a single variable or several variables separated by commas. After creating the function, we can use it with its handle to evaluate the function or pass it as an argument to other functions.
For example, create an anonymous function that evaluates and return the area of a circle:
The function handles variable name is cirarea. There is a one input argument, radius. The body of a function is the expression pi * radius .ˆ 2. The .ˆ array function is used so that the vector of radii can be passed to the functions.
The functions are then called using the handle and passing arguments(s) to it. The function call using a function handle looks just like a function call using a function name.
The type of cirarea can be found using class functions:
Unlike functions saved in code files, if no parameter is passed to an anonymous function, the parentheses must be in the function definitions and in the function calls. For example, the following is anonymous function that print a random real number with two decimal places, as well as call to this function:
Typing the name of the function handle will show its content, which is the function definitions.
An anonymous function can be stored to a MAT-file and can then be loaded when needed.
Custom anonymous functions
Example of an anonymous functions with one independent variable:
The function: can be defined in the command window as an anonymous function for x as a scalar by:
If a semicolon is not typed at the end, MATLAB shows the function. The function can then be used for different values of x:
If x is expected to be an array, and the function calculated for each element, then the function must be modified for element-by-element calculations.
Example of an anonymous function with various independent variables:
The function f (x, y) = 2x2-4xy + y2 can be defined as an anonymous function by:
Then, the anonymous function can be used for particular values of x and y. For example, typing HA (2, 3) gives:
Parameterizing anonymous functions
Variables in the workspaces can be used within the definition of anonymous functions. This is called parameterizing. For example, to use a constant c = 2 in an anonymous function:
f (3) used the variable c as an argument to multiply with the provided x. Note that if the value of c is set to something different at this point, then f (3) is called, the result would not be different. The value of c is the value at the time of the creation of the anonymous function: