Open In App

Local Functions in MATLAB

Last Updated : 03 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads