Horje
Function Handles in MATLAB

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.

 




Reffered: https://www.geeksforgeeks.org


MATLAB

Related
RMSE - Root Mean Square Error in MATLAB RMSE - Root Mean Square Error in MATLAB
How To Export a Matrix as a CSV File in MATLAB? How To Export a Matrix as a CSV File in MATLAB?
How To Hide Message or Image Inside An Image In MATLAB? How To Hide Message or Image Inside An Image In MATLAB?
Importing Data in MATLAB Importing Data in MATLAB
Cell Arrays in MATLAB Cell Arrays in MATLAB

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12