Open In App

Defining Function Handles in MATLAB

Last Updated : 05 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

A MATLAB data type that represents a function is called a function handle, in other words, we say that The function handle is a typical data type in MATLAB. Function handles can therefore be modified and used in the same way as other MATLAB data types. Using function handles in arrays, structures, and cell arrays is a part of this.  Function handles are frequently used to pass a function to another function. Handles for functions can represent named or unnamed functions. For instance, functions that evaluate mathematical expressions over a range of values can take function handles as input arguments. You can create a reference to a function and pass it around like any other variable using the function handle operator.

You can accomplish all of the following with function handles:

  1. Provide other functions with information about function access 
  2. Make sure function evaluations are trustworthy.
  3. Give more people access to the private and internal functions
  4. fewer files that define your functions should be used
  5. enhance repeatable operation performance
  6. constructing handles for anonymous functions that are defined inline rather than stored in a program file

Syntax:

handle = @funcName
handle = @anonymous_func

Description:

  • address = @ A handle to the requested MATLAB function is returned by funcName.
  • constructs an anonymous function and returns a handle to that function when handle = @anonymous_func is used.

Establishing Function Handles:

Put an @ sign in front of the function name to create a handle for it. Create a handle with the name f, for instance, if your function is called myfunc by doing the following:

f = @myfunc;

Using a handle to call a function is the same as calling the function directly. As an illustration, let’s say you have a function called computerectangle that is defined as:

Example 1:

Matlab




function b = computerectangle(a)
b = a^4;
end


Make a handle and call the capability to register the rectangle of four.

Example 2:

Matlab




f = @computerectangle;
x = 8;
y = f(x)


 

Rectangle You can use empty parentheses to call the function if it doesn’t need any inputs, as in

Example 3:

Matlab




z = @ones;
x = z()


 

If the assignment is made without the parentheses, a new function handle is made

Example 4:

Matlab




x = z


 

Anonymous functions can have handles created for them.

Create a handle for an anonymous function that calculates the cube of a number, such as cub, and use that handle to call the anonymous function.

Example 5:

Matlab




cub = @(m) m^3;
a = cub(3)


 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads