Defining Anonymous Functions and Handles
An anonymous function is created inline with the @ symbol: f = @(x) x^2 + 1 defines a function without a separate .m file, useful for short throwaway expressions. You can also create a function handle to an existing named function with @functionName (no parentheses), which lets you pass that function around as a value — store it in a variable, pass it as an argument, or call it later via feval or by invoking the handle directly like f(3).
Cricket analogy: strikeRate = @(runs, balls) (runs/balls)*100 creates an anonymous function on the fly, just like a commentator instantly computing a batsman's strike rate without writing a whole scorecard program
Closures: Capturing Workspace Variables
When you define an anonymous function, MATLAB captures a snapshot of the values of any workspace variables it references at the moment of creation — this is a closure. If you later change the original variable in the workspace, the already-created handle keeps using the old captured value, not the updated one. Creating a new handle after the change would capture the new value instead.
Cricket analogy: addBonus = @(runs) runs + bonusRuns captures the value of bonusRuns at creation time, so later changing bonusRuns in the workspace does not affect the handle, like a scorecard entry locked in at the moment it was recorded
exchangeRate = 83.2;
convertToINR = @(usd) usd * exchangeRate; % captures 83.2 now
fprintf('%.2f\n', convertToINR(100)); % 8320.00
exchangeRate = 90.0; % changing the variable later...
fprintf('%.2f\n', convertToINR(100)); % still 8320.00 - handle kept the old rate
convertToINR_new = @(usd) usd * exchangeRate; % recreated handle captures 90.0
fprintf('%.2f\n', convertToINR_new(100)); % 9000.00Because closures capture values, not references, an anonymous function created inside a loop that refers to the loop variable will each capture that iteration's value correctly in MATLAB — but if you intend a handle to always reflect the CURRENT value of a variable, you must recreate the handle after the variable changes; it will never auto-update.
Passing Handles to arrayfun, cellfun, and feval
Function handles become powerful when passed to higher-order functions. arrayfun applies a handle to each element of a numeric array, cellfun applies a handle to each cell of a cell array, and feval calls a handle stored in a variable dynamically — useful when the function to call is determined at runtime rather than hard-coded. Both arrayfun and cellfun accept 'UniformOutput', false when the handle's outputs aren't uniform scalars.
Cricket analogy: strikeRates = arrayfun(@(r,b) r/b*100, runsArray, ballsArray) applies the strike-rate formula across every player's stats in one vectorized call instead of looping
Handles with fplot, ode45, and Optimization
Many MATLAB toolbox functions accept a function handle as their core argument: fplot(@(x) expr, xrange) plots a mathematical expression directly, ode45(@(t,y) expr, tspan, y0) numerically integrates a differential equation defined inline, and optimization routines like fminbnd(@(x) expr, lower, upper) search for the input minimizing an anonymous objective function. This pattern avoids writing a separate named function file for a one-off mathematical model.
Cricket analogy: fplot(@(x) 100*(1-exp(-0.1*x)), [0 50]) plots a strike-rate acceleration curve against balls faced, feeding the anonymous handle directly into fplot
You can check whether a variable is a function handle with isa(f, 'function_handle'), and inspect its definition text with func2str(f) — handy for debugging pipelines that build anonymous functions dynamically.
- Anonymous functions use @(args) expression syntax; @functionName creates a handle to a named function.
- Anonymous functions form closures, capturing referenced workspace variable values at creation time, not by reference.
- A handle's captured values never update automatically when the source variable later changes.
- arrayfun and cellfun apply a handle across every element of an array or cell array without an explicit loop.
- feval calls a handle stored in a variable, useful for runtime-selected functions.
- Toolbox functions like fplot, ode45, and fminbnd accept handles directly as their core argument.
- func2str() and isa(f,'function_handle') help inspect and validate handles at runtime.
Practice what you learned
1. What syntax creates an anonymous function that squares its input?
2. When an anonymous function references a workspace variable, what does it capture?
3. Which function applies a handle to every element of a numeric array without an explicit loop?
4. What does feval(@myFunc, x) do?
5. Which MATLAB function lets you plot a mathematical expression by passing an anonymous function directly?
Was this page helpful?
You May Also Like
Functions in MATLAB
Learn how to define MATLAB functions with proper file naming, multiple return values, variable input arguments, local function scope, and recursion.
Loops in MATLAB
Master for and while loops in MATLAB, including break/continue, nested loops, preallocation, and iterating cell arrays and structs.
Scripts vs Functions
Understand the key differences between MATLAB scripts and functions — workspace behavior, when to use each, and how to convert a script into a reusable function.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics