10.1.4: Anonymous (or In-Line) Functions
- Page ID
- 95561
There is an option in MATLAB to create an in-line function, without creating a regular function file or subfunction. It only works if the function is simple enpough to be written on a single line of code. The syntax of this option is confusing to most students. This option is never necessary, but can be convenient if the function is a particular function for only 1 script. Such in-line functions are called often "anonymous" functions. This name "anonymous" functions is common, but misleading, since such a function does have a name. (Anonymous functions are an advanced topic and is optional for this textbook.) A general purpose user function should be put in its own file.
Using the example of the previous section, the function can be defined as an in-line function with this syntax:
y_fun1 = @(x) log(x)./x.^2 -0.1;
The left side states the name of the function.
The @(x) states that the function is a function of x.
The rest of the right side is the formula that will be computed.
For an in-line (anonymous) function the function name is the function handle, so when we use it in fzero, we use the name without the @ as shown here:
x_solution = fzero(y_fun1, 4)
.