6.5. Anonymous Functions
Table of Contents
What Anonymous Functions Are
Anonymous functions in MATLAB are functions that you define in a single line, without creating a separate function file. They are created directly in the Command Window, in a script, or inside another function, and are stored in variables like ordinary data. You use them when the function is simple, short, and mainly needed locally.
An anonymous function always has the form
$$
f = @(inputs)\ \text{expression involving inputs}
$$
The symbol @ introduces the function, the parentheses list the input arguments, and the expression on the right defines what the function returns. There is no separate function keyword, no end, and no function file.
Basic Creation and Use
To create a very simple anonymous function that squares a number, you write
square = @(x) x.^2;
Now square is a function handle stored in a variable. You call it using normal function call syntax:
square(3) % returns 9
square([1 2 3]) % returns [1 4 9]The expression on the right can use any valid MATLAB operations, built in functions, and arithmetic that make sense for the inputs. For example, you can define a small polynomial
p = @(x) 2*x.^3 - 3*x + 1;
y = p(1.5);or a function with multiple inputs
hyp = @(a, b) sqrt(a.^2 + b.^2);
hyp(3, 4) % returns 5The number of inputs in the call must match the number of inputs in the definition.
Multiple Inputs and No Inputs
You can define anonymous functions with several inputs by listing them in the parentheses, separated by commas. For instance,
areaRect = @(w, h) w .* h;
areaRect(2, 5) % returns 10You can also define an anonymous function that takes no inputs at all. In that case you still need empty parentheses:
timeNow = @() datetime("now");
t = timeNow();A no input anonymous function is useful if you want to defer evaluation of an expression until later, or when a function argument is required by some other function but the calculation does not actually need external inputs.
Using Anonymous Functions with Other Functions
One of the main uses of anonymous functions is to pass them as inputs to other functions. MATLAB expects function handles as arguments in many places, and anonymous functions are a convenient way to create such handles on the spot.
For example, numerical solvers or optimizers often take a function to evaluate. Suppose you want to integrate the function $f(x) = \sin(x^2)$ from 0 to 1. You can create an anonymous function and pass it directly:
f = @(x) sin(x.^2);
result = integral(f, 0, 1);Or you can pass the anonymous function expression directly without assigning it to a separate variable:
result = integral(@(x) sin(x.^2), 0, 1);
This pattern is common with functions such as integral, fzero, fminsearch, and many others that expect a function handle.
You also use anonymous functions in operations that apply a function to each element or subset of data. For instance, you can use them with arrayfun:
sq = @(x) x.^2;
A = 1:5;
B = arrayfun(sq, A); % applies sq to each element of AIn this way, anonymous functions become small building blocks that you can combine with higher level functions without the overhead of creating separate function files.
Anonymous Functions with Parameters (Captured Variables)
Anonymous functions can refer not only to their explicit inputs, but also to variables that are in the workspace where they are created. These variables become captured by the anonymous function. This lets you create function families that keep certain parameters fixed, while still allowing some inputs to vary.
For example, define a function that represents a straight line with slope m and intercept b. You can write
m = 2;
b = 3;
lineFun = @(x) m*x + b;
y = lineFun(4); % uses m = 2 and b = 3
Here lineFun has one input x, but it still uses m and b. The values of m and b at the time you create lineFun are captured. If you later change m or b, you need to be careful about how MATLAB behaves.
When m and b are simple variables in the same workspace, and you only capture them once, lineFun uses the latest values of m and b as long as they still exist in that workspace. If the workspace goes away, for example when a function that created lineFun finishes, the captured values are stored internally with the handle. In that case lineFun keeps using the values that were in effect at creation time.
A common pattern is to create a more specific function from a general one. For instance, suppose you want a Gaussian function with a fixed standard deviation:
sigma = 2;
gauss = @(x) exp(-(x.^2) / (2*sigma^2));
val = gauss(1);
You can then pass gauss to other functions, and it will always use the same sigma unless you redefine it.
Anonymous Functions in Scripts and Functions
You can define anonymous functions at the Command Window, inside scripts, and inside full function files. Where you define them affects which variables they can see and capture.
In a script, anonymous functions can access variables from the base workspace in which the script runs. For example, if you have
a = 10;
myfun = @(x) x + a;
then myfun(5) gives 15, using the current value of a in the base workspace.
Inside a function file, anonymous functions can capture input arguments and local variables of that function. This is often used to create helper functions that keep some parameters hidden from the outside. For example,
function out = scaleAndSum(x, factor)
scale = @(y) factor * y;
out = sum(scale(x));
end
Here scale is anonymous, it uses factor from the outer function, and it is only visible inside scaleAndSum. When scaleAndSum finishes, scale is no longer accessible from outside, but it was valid while the function ran.
Because anonymous functions depend on the workspace where they are created, they can become invalid if that workspace is cleared. For instance, if you define an anonymous function in the base workspace and then use clear on the variable that holds it, you lose the function handle. If the variables it captures are removed, MATLAB still keeps a private copy for the function handle as long as that handle variable exists, but new handles created later will use the then current values.
Limitations and Characteristics
Anonymous functions are intentionally simple. They have several limitations that distinguish them from regular function files.
An anonymous function can only contain a single executable expression. It cannot have multiple statements separated by semicolons, if blocks, loops, or other control flow structures. Any branching or multi step logic needs a regular function file instead.
Anonymous functions can have only one output, which is the value of the expression. You cannot write something like
f = @(x) [x, x.^2];and expect two separate outputs. Instead, you get a single output that is a vector or array. If you need multiple distinct outputs, use a normal function definition.
You cannot define persistent variables, nested functions, or subfunctions directly inside an anonymous function. These features belong to full function files.
Because anonymous functions are stored in variables, they are subject to the same rules as other variables. Assigning a new value to the same variable name overwrites the old handle. Copying or passing the variable copies the handle, not a separate function. If you save the workspace to a MAT file, the anonymous function handle is saved and can be loaded later, as long as any referenced functions or toolboxes are still available.
Simple Practical Examples
Anonymous functions are useful whenever you want a short, disposable function. Here are a few typical patterns.
To create a quick transformation of a vector without naming a full function, you might write
x = linspace(0, 2*pi, 100);
f = @(t) sin(t) + 0.5*cos(2*t);
y = f(x);
plot(x, y);To filter elements of an array, you can combine an anonymous function with logical indexing or helper functions. For instance, imagine you want all elements greater than their mean:
isAboveMean = @(v) v > mean(v);
A = [1 3 5 7];
mask = isAboveMean(A);
result = A(mask); % returns [5 7]In data fitting, you might wrap a model with fixed parameters and leave only a few coefficients free. An anonymous function lets you express that model concisely and pass it into solvers that expect only a function of the variable of interest.
These small examples illustrate the role of anonymous functions as compact, flexible, and local tools that help you express simple computations directly at the point of use.
Anonymous functions are single expression, one output functions defined inline with the syntax @(inputs) expression. They can capture variables from their creation workspace, and are convenient to pass into other functions. Use them for short, simple operations, and use regular function files when you need multiple statements, multiple outputs, or more complex logic.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Getting Started with MATLAB
- ☰ 1.1. What Is MATLAB and What Is It Used For
- ☰ 1.2. Installing MATLAB and Setting Up the Environment
- ☰ 1.3. Understanding the MATLAB Desktop Interface
- ☰ 1.4. Command Window, Workspace, and Current Folder
- ☰ 1.5. Basic Workflow and Running Simple Commands
- ☰ 1.6. Getting Help and Documentation
-
- ☰ 2. MATLAB Language Basics
- ☰ 2.1. MATLAB Syntax and Expressions
- ☰ 2.2. Variables and Assignment
- ☰ 2.3. Data Types and Type Conversion
- ☰ 2.4. Vectors and Matrices Fundamentals
- ☰ 2.5. Creating and Indexing Arrays
- ☰ 2.6. Basic Arithmetic and Elementwise Operations
- ☰ 2.7. Using Built-In Constants and Functions
-
- ☰ 3. Working with Variables and the Workspace
- ☰ 3.1. Creating, Viewing, and Editing Variables
- ☰ 3.2. Workspace Browser and Variable Inspector
- ☰ 3.3. Saving and Loading Data Files
- ☰ 3.4. MAT-Files and Importing External Data
- ☰ 3.5. Clearing Variables and Managing the Workspace
-
- ☰ 4. Vectors, Matrices, and Arrays
- ☰ 4.1. Row and Column Vectors
- ☰ 4.2. Matrix Creation and Concatenation
- ☰ 4.3. Indexing, Slicing, and Logical Indexing
- ☰ 4.4. Matrix Operations vs Elementwise Operations
- ☰ 4.5. Reshaping and Rearranging Arrays
- ☰ 4.6. Special Matrices and Functions
-
- ☰ 5. Basic Programming Constructs
- ☰ 5.1. Scripts vs Functions
- ☰ 5.2. Control Flow with if, elseif, else
- ☰ 5.3. Loops with for and while
- ☰ 5.4. break, continue, and return
- ☰ 5.5. Logical Expressions and Relational Operators
- ☰ 5.6. Best Practices for Clear and Readable Code
-
- ☰ 6. Functions in MATLAB
- ☰ 6.1. Creating Simple Functions
- ☰ 6.2. Function Inputs and Outputs
- ☰ 6.3. Function Files and the Path
- ☰ 6.4. Local vs Global Variables
- ☰ 6.5. Anonymous Functions
- ☰ 6.6. Organizing Code into Multiple Functions
-
- ☰ 7. Working with Numbers and Math
- ☰ 7.1. Scalars and Vectorized Computations
- ☰ 7.2. Basic Mathematical Functions
- ☰ 7.3. Trigonometric and Exponential Functions
- ☰ 7.4. Complex Numbers in MATLAB
- ☰ 7.5. Rounding, Modulo, and Special Values
- ☰ 7.6. Numerical Precision and Floating Point Considerations
-
- ☰ 8. Strings, Characters, and Categorical Data
- ☰ 8.1. Character Arrays and String Arrays
- ☰ 8.2. Creating and Manipulating Strings
- ☰ 8.3. Converting Between Data Types and Strings
- ☰ 8.4. Comparing and Searching Strings
- ☰ 8.5. Categorical Arrays Basics
-
- ☰ 9. Tables, Structures, and Cell Arrays
- ☰ 9.1. Introduction to Tables
- ☰ 9.2. Creating Tables and Accessing Data
- ☰ 9.3. Modifying and Joining Tables
- ☰ 9.4. Structures and Nested Structures
- ☰ 9.5. Cell Arrays and Cell Indexing
- ☰ 9.6. Choosing the Right Container Type
-
- ☰ 10. Importing and Exporting Data
- ☰ 10.1. Reading Text and CSV Files
- ☰ 10.2. Importing Excel Spreadsheets
- ☰ 10.3. Importing Data with the Import Tool
- ☰ 10.4. Exporting Data to Files
- ☰ 10.5. Working with Image and Audio Files
- ☰ 10.6. Basic File Management from MATLAB
-
- ☰ 11. Plotting and Visualization
- ☰ 11.1. Introduction to 2D Plotting
- ☰ 11.2. Customizing Plots and Axes
- ☰ 11.3. Multiple Plots in One Figure
- ☰ 11.4. Labels, Titles, Legends, and Annotations
- ☰ 11.5. Plotting with Different Line and Marker Styles
- ☰ 11.6. Saving and Exporting Figures
-
- ☰ 12. Advanced Plotting for Beginners
- ☰ 12.1. Subplots and Tiled Layouts
- ☰ 12.2. Bar, Scatter, and Stem Plots
- ☰ 12.3. Histograms and Density Plots
- ☰ 12.4. 3D Plots and Surface Plots
- ☰ 12.5. Using plottools and Interactive Editing
- ☰ 12.6. Basics of Handle Graphics
-
- ☰ 13. Working with Scripts and Live Scripts
- ☰ 13.1. Creating and Running Script Files
- ☰ 13.2. Sectioning Code and Running Sections
- ☰ 13.3. Live Scripts and Rich Text
- ☰ 13.4. Adding Equations, Images, and Outputs
- ☰ 13.5. Sharing and Exporting Live Scripts
-
- ☰ 14. Debugging and Code Quality
- ☰ 14.1. Finding and Fixing Syntax Errors
- ☰ 14.2. Setting Breakpoints and Stepping Through Code
- ☰ 14.3. Inspecting Variable Values During Execution
- ☰ 14.4. Using the Editor Debugging Tools
- ☰ 14.5. Using Code Analyzer and Warnings
- ☰ 14.6. Writing Clean and Maintainable MATLAB Code
-
- ☰ 15. Basic Linear Algebra with MATLAB
- ☰ 15.1. Vectors and Norms
- ☰ 15.2. Matrix Addition and Multiplication
- ☰ 15.3. Solving Linear Systems with Backslash
- ☰ 15.4. Inverses, Determinants, and Rank
- ☰ 15.5. Eigenvalues and Eigenvectors
- ☰ 15.6. Using Linear Algebra Functions Safely
-
- ☰ 16. Data Analysis and Statistics Fundamentals
- ☰ 16.1. Descriptive Statistics and Summary Measures
- ☰ 16.2. Sorting, Filtering, and Grouping Data
- ☰ 16.3. Basic Correlation and Regression
- ☰ 16.4. Simple Data Cleaning Techniques
- ☰ 16.5. Basic Time Series Handling
-
- ☰ 17. Working with Time and Dates
- ☰ 17.1. Representing Dates and Times
- ☰ 17.2. Creating and Formatting datetime Arrays
- ☰ 17.3. Date Calculations and Differences
- ☰ 17.4. Plotting Data over Time
-
- ☰ 18. Introduction to Signal and Image Handling
- ☰ 18.1. Basic Signal Representation in MATLAB
- ☰ 18.2. Simple Filtering and Transformations
- ☰ 18.3. Reading, Displaying, and Writing Images
- ☰ 18.4. Basic Image Transformations
-
- ☰ 19. Automation and Scripting Tasks
- ☰ 19.1. Batch Processing of Files
- ☰ 19.2. Writing Reusable Utility Scripts
- ☰ 19.3. Using Relative Paths and the MATLAB Path
- ☰ 19.4. Simple User Interaction with input and disp
-
- ☰ 20. Introduction to Toolboxes
- ☰ 20.1. What Are Toolboxes and How to Use Them
- ☰ 20.2. Exploring Installed Toolboxes
- ☰ 20.3. Finding Functions in Toolboxes
- ☰ 20.4. Add-Ons and MATLAB File Exchange
-
- ☰ 21. Best Practices and Next Steps
- ☰ 21.1. Organizing Projects and Folders
- ☰ 21.2. Version Control Basics with MATLAB
- ☰ 21.3. Performance Tips for Beginners
- ☰ 21.4. Learning Resources and Documentation Path
- ☰ 21.5. Suggested Practice Projects for Beginners
-
Comments
Please login to add a comment.
Don't have an account? Register now!