Computers

Function Handle in Octave

Function Handle in Octave

A function handle is a data type that stores an association with a function. You can use a function handle to construct anonymous functions, pass a function to another function, or call local functions from outside the main function.

In this example, we will see how to create a handle for a function and Pass Function to another Function.

Simple Function to calculate:

y=m*x + c

StraightLine Function

function [x,y]= StraightLine(lower,upper)

x= linspace(lower,upper,100);

% Calculate y

y= 10.*x + 5;

end

 

The StraightLine function takes two input arguments; lower and upper
x vector has 100 values between lower and upper bounds. It calculates the vector y as per the straight-line equation

y = 10*x + 5
Outputs: Vector x and y

Let’s create another function to accept the handle and plot the graph for x vs y.

FunctionHandleDemo

function [x,y] = FunctionHandleDemo(f,arg1,arg2)

[x,y] = f(arg1,arg2);

%plot

plot(x,y,'g+');

%labels

xlabel('x');

ylabel('y');

% Plot title

title('Function handle Example');

end

 

 

Description of the function:

FunctionHandleDemo accepts Three Input arguments
function handle f
Two input integer arguments arg1 and arg2

Outputs: vectors x and y
Plots x vs y
It invokes the function with arguments arg1 and arg2

Driver script

We need a script to invoke the method above with the function handle.

handle = @StraightLine;
%pass handle,10,20
FunctionHandleDemo(handle,10,20);