Opening the book…
An anonymous function is a short function that is created directly in a script, in the Command Window, or inside another function file. Unlike regular functions, anonymous functions do not need their own separate .m file.
Anonymous functions are useful when you need to define a simple mathematical expression and use it several times. They are especially helpful when working with plotting, numerical integration, root finding, and other numerical methods.
The basic format is:
functionName = @(inputVariable) expression;
The symbol @ tells MATLAB that we are creating a function handle. A function handle is a variable that stores a reference to a function. The input variable is placed inside parentheses after the @ symbol.
For example, to define
\(f(x) = 3*x^2 + 2*x - 1\)
we write:
f = @(x) 3*x.^2 + 2*x - 1;
After creating the anonymous function, we can evaluate it just like we would call any other function.
For example:
f(2)
returns:
12
because:
2^2 + 3(2) + 2 = 12
We can also pass an array of values to the function:
x = 0:5; y = f(x)
This evaluates the function at every value in the vector x.
Notice the element-by-element operator .^ in the function definition. This allows the function to work with both single numbers and arrays of x-values.
When writing anonymous functions that may receive arrays, use element-by-element operations such as .*, ./, and .^ when appropriate.
Anonymous Functions with More Than One Input
Anonymous functions can also have more than one input. For example, suppose we want to define the area of a rectangle as a function of width and height.
Calculating the area of one or many rectangles.
Solution

This page titled 12.6: Anonymous Functions was last modified on Tue, 30 Jun 2026 02:11:51 GMT and is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Zara Noroozi.
The book could not be loaded just now.