Anonymous functions in MATLAB are compact, single-line functions that can be defined without creating a separate file. They are particularly useful for simple operations and as arguments to other functions.
The basic syntax for creating an anonymous function in MATLAB is:
function_handle = @(input_args) expression
Here's a simple example of an anonymous function that squares a number:
square = @(x) x.^2;
result = square(5); % result is 25
Anonymous functions can accept multiple input arguments. Here's an example of a function that calculates the hypotenuse of a right triangle:
hypotenuse = @(a, b) sqrt(a^2 + b^2);
result = hypotenuse(3, 4); % result is 5
Anonymous functions are often used with MATLAB's built-in functions that accept function handles as arguments. For example, with the fzero
function to find roots:
f = @(x) x^2 - 4;
root = fzero(f, 1); % finds the root near x = 1
Anonymous functions can capture variables from the current workspace, allowing for dynamic function creation:
a = 5;
f = @(x) a * x^2;
result = f(2); % result is 20
To further enhance your understanding of MATLAB functions, explore these related topics:
By mastering anonymous functions, you'll have a powerful tool for creating concise, inline operations in your MATLAB code, enhancing both readability and functionality.