English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Functions in MATLAB

A function is a set of statements that perform a task together. In MATLAB, functions are defined in separate files. The file name should be the same as the function name.

Functions operate on variables in their own workspace (also known as local workspace) and are different from the workspace accessed at the MATLAB command prompt (known as the base workspace).

Functions can accept multiple input parameters and can return multiple output parameters.

The syntax of the function statement is-

function [out1, out2, ..., outN] = myfun(in1, in2, in3, ..., inN)

Online Example

The following namedmymax'sThe function should be written in a file namedmymax.mThe file takes five numbers as parameters and returns the largest number.

Create a function file named mymax.m and enter the following code-

function max = mymax(n1, n2, n3, n4, n5)
% This function is used to calculate
% Input five numbers
max = n1;
if(n2 > max)
   max = n2;
end
if(n3 > max)
   max = n3;
end
if(n4 > max)
   max = n4;
end
if(n5 > max)
   max = n5;
end

The first line of the function starts with the keyword function begins . It gives the name and order of the parameters of the function. In our example,mymaxThe function has five input parameters and one output parameter.

The comment lines after the function statement provide help text. When you enter the following, these lines will be printed:

help mymax

MATLAB will execute the above statements and return the following result-

This function calculates the maximum of the
   five numbers given as input

You can call the function-

mymax(34 78 89 23 11)

MATLAB will execute the above statements and return the following result-

ans = 89

Anonymous functions

Anonymous functions are like inline functions in traditional programming languages and are defined in a single MATLAB statement. They consist of a MATLAB expression and any number of input and output parameters.

You can directly define anonymous functions in the MATLAB command line or in functions or scripts.

In this way, you can create simple functions without having to create a file for them.

The syntax for creating an anonymous function from an expression is

f = @(arglist)expression

Example

In this example, we will write an anonymous function named 'power' that takes two numbers as input and raises the first number to the power of the second number.

Create a script file and enter the following code-

power = @(x, n) x.^n;
result1 power(7 3)
result2 power(49, 0.5)
result3 power(10 -10)
result4 =4.5 1.5)

When the file is run, it displays-

result1 =  343
result2 =  7
result3 =  1.0000e-10
result4 =  9.5459

Main and Sub-functions

Any function except anonymous functions must be defined in the file. Each function file contains a required main function that appears first, followed by any number of optional sub-functions that are used after the main function.

The main function can be called from outside the file definition (from the command line or other functions), but sub-functions cannot be called from outside the function file from the command line or other functions.

Subfunctions are only visible to the main function and other subfunctions defined in the function file in which they are defined.

Example

Let's write a function named quadratic to calculate the roots of a quadratic equation. The function has three inputs: quadratic coefficient, linear coefficient, and constant term. It will return the roots.

The function file quadratic.m will contain the main function quadratic and the subfunction disc, which calculates the discriminant.

Create a function file quadratic.m and enter the following code inside it

function [x1,x2] = quadratic(a,b,c)
% This function returns
% a quadratic equation.
% It needs3input parameters
% x2, x and
% Constant term
% It returns the roots
d = disc(a,b,c); 
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end  % End of quadratic
function dis = disc(a,b,c) 
% Function calculates the discriminant
dis = sqrt(b^2 - 4*a*c);
end  % End of sub-function

You can call the above function from the command prompt as follows:

quadratic(24-4)

MATLAB will execute the above statements and return the following result-

ans = 0.7321

Nested functions

You can define a function within the body of another function. These are called nested functions. Nested functions contain any or all components of any other function.

Nested functions are defined within the scope of another function, and they share access to the workspace of the containing function.

Nested functions follow the following syntax-

function x = A(p1, p2)
...
B(p2)
   function y = B(p3)
   ...
   end
...
end

Example

Let's rewrite the previous example'squadraticfunction. However, this time, the disc function will be a nested function.

Create a function filequadratic2.m,and enter the following code inside it-

function [x1,x2] = quadratic2(a,b,c)
function disc  % Nested function
d = sqrt(b^2 - 4*a*c);
end  % End of function disc
disc;
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end  % End of function quadratic2

You can call the above function from the command prompt as follows:

quadratic2(24-4)

MATLAB will execute the above statements and return the following result-

ans = 0.73205

Private functions

Private functions are main functions that are only visible to a limited set of other functions. If you do not want to expose the implementation of the function function(s), you can create them as private functions.

Private functions are located in a subfolder with the special name Private.

They are only visible to functions in the parent folder.

Example

Let's rewritequadraticThe function. However, this time, the disc function calculates the discriminant and will be a private function

Create a subfolder named private in the working directory folder, and store the following function file disc.m inside it

function dis = disc(a,b,c) 
% Function calculates the discriminant
dis = sqrt(b^2 - 4*a*c);
end  % Subfunction ends

Create a function named quadratic in your working directory3.m, and enter the following code inside it-

function [x1,x2] = quadratic3(a,b,c)
% This function returns
% A one-variable quadratic equation.
It needs3input parameters
% They are the x2,x and
% The constant term
% It returns the roots
d = disc(a,b,c); 
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end % End quadratic3

You can call the above function from the command prompt as follows:

quadratic3(24-4)

MATLAB will execute the above statements and return the following result-

ans = 0.73205

Global Variables

Global variables can be shared by multiple functions. To do this, you need to declare the variable as a global variable in all functions.

If you need to access the variable from the basic workspace, declare the variable in the command line.

Global declarations must occur before the variables are actually used in the function. It is best to use uppercase letters for the names of global variables to distinguish them from other variables.

Example

Let's create a function file named average.m and enter the following code-

function avg = average(nums)
global TOTAL
avg = sum(nums)/TOTAL;
end

Create a script file and enter the following code-

global TOTAL;
TOTAL = 10;
n = [34 45 25 45 33 19 40, 34 38 42]
av = average(n)

When running the file, it will display the following result-

av =  35.500