Introduction to Functions
The goal of this tutorial is to explain how to create a MATLAB function. Function is a set of statements that performs a specific task. MATLAB has thousands of builtin functions like sin(), log(), randn(). MATLAB also allows the programmer to create their own functions. Creating function allows reuse of a set of commands without having to rewrite them every time. Functions are usually defined and stored in separate files using a standard format.
Syntax of MATLAB function
Lets look at the syntax of a MATLAB function.
function [output1,output2,...] = function_name(input1,input2,...) statement1; statement2; ... end
Function consists of the following parts
- The definition of the function must start with the keyword function
- function keyword is followed by a list of function outputs inside square brackets. These are the values that are “returned” by the function.
- Then the name of the function is given
- function name is followed by a list of function inputs inside round brackets
- The main body of the function starts in the next line. Main body can consist of one or more statements
- end keyword indicates the end of the function. end is not always required but it is better to use it
How to create a MATLAB Function – Examples
Lets create a function that takes radius of a sphere as input and outputs the area of a sphere. This function requires a single input and has a single output. The square brackets around the output variable are optional if there is a single output.
function area = area_sphere(radius) area = 4*pi*(radius^2); end
The function should be saved in a separate script named “area_sphere.m” i.e, the name of the script file should be same as the function name. Function can now be called from another script, command window or another function. Running the “area_sphere.m” directly will return an error “Not enough input arguments”. This happens because the function requires some inputs. When you run it directly, those inputs are not provided.
>> area_sphere Not enough input arguments. Error in area_sphere (line 2) area = 4*pi*(radius^2);
Lets call the function from the command window and provide the proper input. The output will be shown in the command window since we have omitted the semicolon at the end of the statement calling the function.
>> area_sphere(2) ans = 50.2655
The answer is correct and MATLAB has stored the area in the variable ans. Another way of using the same function is
>> a = area_sphere(2) a = 50.2655
Now MATLAB stores the calculated area in the variable a specified by us.
Lets create another function that calculates both area and volume of the sphere. This is an example of a function that returns multiple outputs.
function [area,volume] = area_volume_sphere(radius) area = 4*pi*(radius^2); volume = (4/3)*pi*(radius^3); end
Lets try calling it and see if it returns both area and volume or not
>> area_volume_sphere(2) ans = 50.2655
Our function is returning only the area i.e, the first output. We have not written the statement that calls the function correctly. As a result MATLAB is discarding the second output (volume) and assigning the first output (area) to ans variable. To save both outputs, the correct way of calling the function is
>> [a,v] = area_volume_sphere(2) a = 50.2655 v = 33.5103
Now MATLAB is saving both outputs in variables a and v respectively.
Lets see an example of a function with multiple inputs, one of which is a vector.
function y = quadratic_equation(coeff,x) y = coeff(1)*(x^2) + coeff(2)*x + coeff(3); end
While calling the function, the sequence of the given inputs should be the same as in the function definition for error free execution / correct result. If we call the function from the command window and interchange both inputs, we will get an error. MATLAB expects a vector as first input and a scalar as second input.
>> y = quadratic_equation(2,[3 1 5]) Error using ^ One argument must be a square matrix and the other must be a scalar. Use POWER (.^) for elementwise power. Error in quadratic_equation (line 2) y = coeff(1)*(x^2) + coeff(2)*x + coeff(3);
Now lets call the function correctly.
y = quadratic_equation([3 1 5],2)
The output will be shown in the command window since we have omitted the semicolon at the end of the statement calling the function.
y = 19
Now lets look at an example which doesn’t require any input.
function r = randn_10() r = randn(1,10); end
This function returns a vector of 10 values from the normal distribution.
>> randn_10() ans = 0.5377 1.8339 -2.2588 0.8622 0.3188 -1.3077 -0.4336 0.3426 3.5784 2.7694
Your values will be different as this function generates random numbers. Since this function doesn’t require any input, you can directly run the script file from the editor as well.
If you run this function and provide an input then MATLAB returns an error “Too many input arguments”.
>> randn_10(3) Error using randn_10 Too many input arguments.
Lets look at a function without any output.
function average_randn(n) average = sum(randn(1,n))/n end
This function simply generates “n” numbers from the normal distributions and displays their average (since we omitted the semicolon) without returning any values.
>> average_randn(1000) average = 0.0287
Running the function and assigning the output to a variable returns an error “Too many output arguments”.
>> a = average_randn(1000) Error using average_randn Too many output arguments.
Example 6: Create a MATLAB function at the end of any .m file
Starting from MATLAB R2016b, function can be defined at the end of any .m file. Name of the function and the file doesn’t need to be same.
a = area_sphere(2) function area = area_sphere(radius) area = 4*pi*(radius^2); end
Running the file gives the following output
>> main a = 50.2655
Important points to remember
- MATLAB function should be written in a separate file. The name of the function and that of the .m file must be same. Starting from MATLAB R2016b, functions can also be defined at the very end of a script file.
- Outputs are optional. They can be omitted if the function doesn’t return any outputs.
- Inputs are also optional. They can be omitted if the function doesn’t require any inputs.
- Function must be called from another script, MATLAB function or command window. Running the “function_name.m” directly will return an error. This happens because the function requires some inputs. When you run it directly, those inputs are not provided.
- You must either save the file in the current folder or in another folder which is included in MATLAB search path. This is necessary for MATLAB to find the function when you run scripts or commands that use the functions
- Functions have their own workspace which is separate than the base workspace.
- The variables declared/defined inside the function are not accessible outside the function. If a variable is outputted then a copy is saved in the main workspace.
- The variables outside the function are not accessible inside the function. However, a copy can be passed to the function as inputs.
That is all for this tutorial. You can find my other MATLAB tutorials here.