MATLAB - Anonymous Functions
MATLAB - Anonymous Functions
Section titled “MATLAB - Anonymous Functions”An anonymous function is a simple, one-line function that is not stored in a separate .m file. They are incredibly useful for defining quick calculations or for passing a function as an argument to another function (like for integration or optimization). They are also known as lambda functions in other programming languages.
Anatomy of an Anonymous Function
Section titled “Anatomy of an Anonymous Function”The syntax is concise and powerful:
function_handle = @(arg1, arg2, ...) expression;function_handle: The variable that stores the anonymous function.@: The symbol that creates the anonymous function.(arg1, arg2, ...): The list of input arguments.expression: The single MATLAB expression that is executed and returned.
Example: Function with One Variable
Section titled “Example: Function with One Variable”Let’s define a function to calculate the area of a circle.
% Define the anonymous functioncircleArea = @(radius) pi * radius^2;
% Use the functionarea1 = circleArea(5);fprintf('The area of a circle with radius 5 is %.2f\n', area1);Example: Function with Multiple Variables
Section titled “Example: Function with Multiple Variables”Here’s an anonymous function to calculate the hypotenuse of a right triangle.
% Define the anonymous functionhypotenuse = @(a, b) sqrt(a^2 + b^2);
% Use the functionhyp = hypotenuse(3, 4);fprintf('The hypotenuse for sides 3 and 4 is %d\n', hyp);Example: Function with No Variables
Section titled “Example: Function with No Variables”You can create a function that returns a constant value, which can be useful as a placeholder or simple generator.
% Returns a timestamp every time it's calledgetTimestamp = @() datetime('now');
% Use the functiontimestamp1 = getTimestamp();disp(timestamp1);Key Advantage: Capturing Workspace Variables (Closures)
Section titled “Key Advantage: Capturing Workspace Variables (Closures)”A powerful feature of anonymous functions is that they can ‘capture’ or ‘enclose’ variables from the workspace where they are defined. This allows you to create parameterized functions without passing the parameters every time.
% Define a parametergain = 10;offset = 5;
% This anonymous function captures 'gain' and 'offset'linearTransform = @(x) gain * x + offset;
% Now use the function. Note we only need to pass 'x'.result = linearTransform(3); % Calculates 10 * 3 + 5fprintf('The result of the transform is %d\n', result);
% You can even change the parameter and create a new functiongain = 100;newTransform = @(x) gain * x + offset;newResult = newTransform(3); % Calculates 100 * 3 + 5fprintf('The new result is %d\n', newResult);Practical Applications: Passing Functions as Arguments
Section titled “Practical Applications: Passing Functions as Arguments”The primary use of anonymous functions is to pass them to other functions that expect a function handle as input. This is common in numerical methods.
Application 1: Numerical Integration with integral
Section titled “Application 1: Numerical Integration with integral”Suppose you want to find the integral of sin(x^2) from 0 to pi, without creating a separate .m file for the function.
% Define the function to integrate directly in the callresult = integral(@(x) sin(x.^2), 0, pi);
fprintf('The integral of sin(x^2) from 0 to pi is %.4f\n', result);Application 2: Finding Function Minimums with fminsearch
Section titled “Application 2: Finding Function Minimums with fminsearch”Let’s find the minimum of the Rosenbrock function, a classic optimization test case.
% Rosenbrock's 'banana' functionbanana = @(x) (1-x(1))^2 + 100*(x(2)-x(1)^2)^2;
% Find the minimum, starting from the point [-1, 2]startPoint = [-1, 2];[min_coords, min_value] = fminsearch(banana, startPoint);
fprintf('Minimum found at (%.2f, %.2f) with value %.4e\n', min_coords(1), min_coords(2), min_value);Application 3: Element-wise Operations with arrayfun
Section titled “Application 3: Element-wise Operations with arrayfun”Applying a simple operation to each element of an array.
% Define an array of numbersnumbers = [1, 2, 3, 4, 5];
% Use an anonymous function to apply a condition to each element% Returns a logical array (1 for true, 0 for false)is_even = arrayfun(@(n) mod(n, 2) == 0, numbers);
disp('Original numbers:');disp(numbers);disp('Is the number even?');disp(is_even);