Horje
Local Functions in MATLAB

Functions in any programming language are some blocks of code, which could be reused whenever required, by just calling the name. It reduces so much of human effort and also rewriting of the same code, and makes the entire code big.

Declaring a function:

Before moving forward let’s see how actually to declare a function in Matlab. The syntax for declaring a function in MATLAB is:

Syntax:

function [x1,x2,...,xn] = myfunc(k1,k2,...,km)

Let’s understand the syntax first. Here, myfunc is the name of the function. The x1,x2,…,xn are the parameter that is sent to the function, and k1,k2,…,kn are the output obtained. For example, a function of adding two numbers in MATLAB, make a function file named multiply.m and write the following code:

Example 1:

Matlab

% MATLAB code for function
function x = multiply(a,b)
 
   x= a*b;
 
end

 
 

Output:

 

Let’s call this function from the command line:

 

Local Function:

MATLAB files are compatible with more than function. When you use Local functions, there is the main function, along with the other local functions. Such local functions are visible to the main function only and cannot be called from the command line.

 

Example 2:

 

Matlab

% MATLAB code for Local function declaration
function [sub, div] = operations(x,y)
sub = subtract(x,y)
div = divide(x,y)
end
 
function z = subtract(x,y)
z = x-y
end
 
function k = divide(x,y)
k = x/y
end

 Output:

Here, save the file with the name of the main function, as in our condition we have to name it our file as operations.m. We can call this function from the command line to execute. However, you can not call the local functions from the command line. 

If you require to check the exact location of your local function then you check it in the command line, by specifying both the names main as well as the local function separated by a ‘>’. Let’s have a look at how actually can we perform this.

Matlab

% MATLAB Code
help operations>subtract
 
% subtract is a local function.
z= subtract(x,y)

Output:

sub = 1278



Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
Relationship Between Parliament and Judiciary Relationship Between Parliament and Judiciary
National Commission For Backward Classes (NCBC) National Commission For Backward Classes (NCBC)
Constructive Programmes of Mahatma Gandhi Constructive Programmes of Mahatma Gandhi
What is String interpolation in CoffeeScript ? What is String interpolation in CoffeeScript ?
How to display table data in stripes and strokes format in jQuery Mobile ? How to display table data in stripes and strokes format in jQuery Mobile ?

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