Control Functions

A function is a file type in MATLAB, which undertakes a series of tasks and returns values. Functions are useful at doing repetitive tasks to a data series saving time on calculations and also reducing the number of lines of code required in the main calling code.

A function normally requires an input and output argument. However, output arguments may not be needed as the function may not produce a value.

The function workspace contains local variables, whereas the workspace which calls the function contains the ‘global’ variables, and is known as the base workspace. Note that it is key to distinguish between local and global variables. The global variables are usable by the main script and functions, whereas the local variables are ‘seen’ only by the function.

To create a function file, open the ‘home’ tab, click new, and then function. Then a new window will open, the editor, where you can write the function code. It will look like this:

 

Function File

output_args refers to the output variables from the function. input_args refers to the variables input from the base script into the function. Untitled is the function name and can be changed, but make sure it is the same as the file name.

To use a function, you need the base script to call the function. To call a function in the base script, the syntax is of the form

function [ output_args ] = Untitled ( input_args )

In the function file you can perform calculations, manipulate variables and display statements, like a normal script. Download and have a look at the examples below:

Quadratic Example

Data Manipulation Example

On a final note, it is possible to have two separate functions in a function file, but there should only be one “end” in the file. To learn more about functions check out these links:

Functions in files

MATLAB Functions

These above links relate to sources that were used as a basis in the production of this tutorial.

Example:

Create a base and function script that will solve a set of linear simultaneous equations that are input by the user. Note that there are many ways to do this, so if your solution differs there is no need to worry.

Tip: The purpose of the function is to solve the set of simultaneous equations.

Tip: Make sure that you know how to express the simultaneous equations in matrix form. If not a simple search online can show you how to do so.

Solution:
[Show]