Function handles are a powerful feature in MATLAB that allow you to treat functions as variables. They provide a way to reference functions directly, enabling more flexible and dynamic programming.
To create a function handle, use the @ symbol followed by the function name:
fh = @sin;
This creates a handle to the built-in sine function. You can also create handles to your own functions:
function result = myFunction(x)
result = x^2 + 2*x + 1;
end
fh = @myFunction;
Once you have a function handle, you can use it like a regular function:
y = fh(2); % Calls myFunction(2)
Function handles are particularly useful when passing functions as arguments to other functions, such as in MATLAB's Built-in Functions like fzero or fminbnd.
MATLAB also allows you to create Anonymous Functions, which are function handles defined inline:
square = @(x) x.^2;
result = square(3); % Returns 9
Here's an example using function handles with MATLAB's integral function:
f = @(x) exp(-x.^2);
area = integral(f, 0, 1);
This calculates the integral of e^(-x^2) from 0 to 1 using a function handle.
Function handles in MATLAB provide a flexible way to work with functions as data. They are essential for advanced programming techniques and are widely used in various MATLAB applications. By mastering function handles, you can write more efficient and versatile MATLAB code.