Call Us On : +91 9873543020    [email protected]

## Introduction

In mathematics, a function is a relation between a set of inputs and the corresponding outputs. It is usually denoted as f(x). MATLAB functions are similar to the mathematical function as they take inputs as arguments, perform operations on them and produce the outputs. There are some built-in functions in MATLAB like sum(x), min(x), sin(x), etc. However, you can make your own user-defined MATLAB functions. In this tutorial, we will discuss the implementation and usage of the user-defined MATLAB functions.

## Creating a user-defined MATLAB function

You can create a function file in two ways:

1. Click on ‘New’ below the + icon at the top left of the MATLAB window and choose ‘Function’ as shown below. An untitled function page will open in the editor as follows.

2. Open a new editor window by pressing ‘CNTR+N’. In this case, you have to write the syntax of the function by yourself.

## Structure of a function file

Let’s take the example of the sample function file of Fig 7.1. The first line is the function definition line. It must start with ‘function’ in lowercase (highlighted in blue). Following this, there is a list of output arguments in square brackets. Here we have two output arguments – outputArg1 and outputArg2. If there is only one output argument, no bracket is required. Then on the right-hand side of the equality, the function name is written following the input arguments in the parenthesis. The function name in the example is ‘untitled’ and there are two input arguments- inputArg1 and inputArg2.

The next line is the first comment line, also called the H1 line. It contains a short description of the function. Following the H1 line, you can write the help text lines that contain a detailed explanation of the function. The H1 line and the help text lines are optional. Then the function body is written. This is the main part of the program that performs the computations. The sample function in the figure is a buffer function where the output arguments are equal to the input arguments.

At the end of the function, you should write the ‘end’ command but it is optional if there is no other function in the same file. Yes, you can write multiple functions (called subfunctions or local functions) in one file and in that case, each function should end with the ‘end’ command.

## Saving a function file

Once you are done writing a function, click on the Save icon or press ‘CNTR+S’. It automatically takes the file name as the function name. And it highly recommended that the file name should be the same as the function name. The file extension for the function file is also .m, same as the script file.

Note that the structure of a function in terms of the input and the output arguments may vary according to the requirements. For example, you can have multiple input arguments and multiple output arguments, single input and/or multiple output arguments and vice versa. Also, you can have no output arguments or no input arguments.

## Calling a user-defined function

The syntax for calling a function is similar to what is written in the function definition line without using the word ‘function’.

[output\_arguments] = function\_name( input\_arguments )

The input and the output argument ‘names’ may or may not be the same as defined within the function. Although the relation between the input and output will be the same as defined in the function.

Note – While calling a fucntion, make sure that the function file is saved in the current folder. Otherwise, you’ll get an error – function not found. So if accidently you saved the function somewhere else in the drive, move the file to the current folder and then you can use it in the commands.

Let’s take a few examples to clarify all the concepts relating to the MATLAB functions.

### Example 1: Function to calculate the distance between two points

Problem: To find the distance between two points (x1,y1) and (x2,y2)

Let’s take two points P1 and P2 both having their x and y coordinates.

P1 = [2 3];     % coordinate of first point with x=2 and y=3
P2 = [6 7];     % coordinate of first point with x=6 and y=7

We want to find the distance between the points. Let’s define a function for calculating distance.

function dist = CalculateDist(P1,P2)
% This function calculates the distance between two points.
% Points P1 and P2 are the row vectors, each of size 2. First element
% is the x coordinate and the second element is the y coordinate.
x1 = P1(1);
y1 = P1(2);
x2 = P2(1);
y2 = P2(2);

dist = sqrt((x1-x2)^2 + (y1-y2)^2);
end

P1 and P2 are the input arguments. dist is the output argument and the CalculateDist is the function name. The first commented line is the H1 line and the next two are the help text line with input details. In lines 4-7, intermediate variable assignments are done to make the code simpler. The distance formula is implemented in line no. 9. Save the function as CalculateDist.m.

To use the function, write the following command.

D = CalculateDist(P1,P2)

The output after running above command is,

D =
5.6569

You can take other points with different names. For example,

P3 = [5.2 12.7];
P4 = [3.1 9.5];
D1 = CalculateDist(P3,P4)

D1 =         % output
3.8275

### Example 2: Find statistical parameters from a data vector

Problem: To find the mean, median and standard deviation from a given vector of data.

Let’s create random data of integers with 10 elements.

clc      % clear the screen
clear    % clear the existing variables

data = randi(20,1,10)  % 20 is the maximum value of the elements. 1-row, 10-columns

data =
17    19     3    19    13     2     6    11    20    20

The function to calculate the statistical parameters is

function [Mn,Md,Sd] = StatisticalParams(data)
% Mn - mean, Md - median, Sd - standard deviation
Mn = mean(data);
Md = median(data);
Sd = std(data);
end

Finding the parameters using the function

[mn,md,sd] = StatisticalParams(data)

mn =        % outputs
13
md =
15
sd =
7.1492

Create your own functions and check the outputs.

## Local and Global variables

All the variables used inside a function are local variables. This means that you don’t have access to any of the intermediate variables used in the function, in the workspace. MATLAB allocates a separate memory to these variables that are not accessible in the command window. Therefore, each function file has its own local variables which can not be shared with each other.

However, you can make a variable ‘global’ if you want it to be shared with other functions or the workspace. You can do it using the following command.

global   variable\_name

You can make several variables global by writing them one after another with a spacing. For example,

global   var1   var2   var3

You should keep the following points in mind while using the global command.

• You should make the variable global before you use it. It is recommended that you define them at the starting of the program.
• You should declare the variables global wherever you wish to share them.
• If you want a variable to be recognized in the workspace using global, declare it either in the command window or the script file before using it.
• You can re-assign the global variables wherever you have assigned them.

## Anonymous Functions

Sometimes, relatively small expressions are repeated frequently in the program. You can define these expressions in the user-defined functions. But if there are plenty of such expressions, you’ll end up having a lot of separate function files. In contrast, you can define an anonymous function in one line of code and you do not need a separate file for it. Also, you can define and use the anonymous functions in a script file, in the command window, or even inside a regular user-defined function.

The syntax of an anonymous function is as follows.

function\_name = @ (argument\_list)   expression

Let’s take a few examples of anonymous functions.

parabola = @ (x) 4*x^2

This command implements the given expression for the parabola. To use it in the program, you need to pass the value of x with the function name. For example,

y = parabola(4)
y =           % output
64
y1 = parabola(10)
y1 =          % output
400

Similarly, you can define expression with multiple variables,

circle = @(x,y) 4*x^2 + 9*y^2

And call the function as,

y = circle(1,2)
y =             % output
40
y1 = circle(0,0)
y1 =            % output
0

## Function Handles

A function handle is an entity that is associated with a function. The objects created using function handles inherits all the properties of the function. Let’s understand the concept using some examples.

• myfunc = @cos: Here myfunc is a function handle of the built-in function cos. To use this, you should write
y = myfunc(pi/3)
y =              % output
0.50         % equals cos(pi/3)
• stats = @StatisticalParams: Here StatisticalParams is the function that we have defined in the previous section. Therefore, a function handle can be generated using a user-defined function also. Let’s look at the example,
stats = @StatisticalParams;
data = randi(100,1,10)      % random data of length 10 with maximum value of elements being 100
[data_mean,data_median,data_std] = stats(data);

So we have discussed the MATLAB functions in detail with examples. You can explore more topics on the function like local functions here and nested functions here.

Thank you.

Contact us!

For training, Research Assistance, and Consultancy Services on Computer Vision, Deep Learning, Signal Processing, Image Processing, and Medical Signal/Image Processing.