Open In App

Function Handles in MATLAB

Last Updated : 18 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Function Handles are a data type of MATLAB which represents a function. They store a function just like an ordinary variable store numeral or alphabetic data. An example of the same could be a function, say f1, that takes another function, f2, as its parameter; f2 calculates a mathematical function over some range. This is just one of the many ways, one could use function handles in MATLAB. Let us see how these function handles are created and used in MATLAB.

Creating Function Handles:

Function handles can be created using the @ operator. The syntax is as follows:

% function
function func = <func_name>(parameters)
%expressions
end

%function handle
fh = @<func_name>

Now, see the following examples for Function Handles. Let us first create a simple handle that calls a function fun which calculates the cube of a given number.

Example 1:

Matlab




% MATLAB Code for Function Handles
  fh = @fun;
  fh(4)
  
% Function
    function res = fun(x)
    res=x^3;
end


Output:

This creates a function handle fh for the fun function. This would give the result as follows:

 

Now let us do some better use of the function handle by passing it to another function.

Example 2:

Matlab




% MATLAB Code for Create a function handles
    fh=@fun;
  
% Passing the handle to the integral
% function over range 0,3
    integral(fh,0,3)
  
% Function
    function res=fun(x)
    res=x.^3;
end


Output:

This would calculate the integral of the cube of x over the range 0 to 3.

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads