A function is a reusable piece of code characterized by a name, a set of inputs, and a set of outputs.

## Preparation

Copy and paste the following codes in two files named ‘myfun.m’ and ‘mycomparer.m’. Guarantee that both files are in the current directory or in the search path.

``````% Copy and paste in 'mysum.m'
function R = mysum(x,y)
R = x + y;
end``````
``````% Copy and paste in 'mycomparer.m'
function[minVal,maxVal] = mycomparer(x,y,z)
minVal = min([x,y,z]);
maxVal = max([x,y,z]);
end``````

## Syntax

To call a function, provide a correct number of inputs and outputs according to its definition. The inputs can be in the form of values or variables, but the outputs must be variables.

The file of the function must be in the current directory or in the search path.
``````% Call the built-in 'sqrt' function
squareRoot = sqrt(4);``````

## Examples

The function `mysum` introduced before receives two scalar numeric inputs and returns the sum of both values. The function `mycomparer` receives three scalar numeric inputs, and returns two outputs containing the minimum and the maximum value in the input.

``````% Call 'mysum', passing two values
sum1 = mysum(2,3);``````
``````% Call 'mysum', passing a value and a variable
a = 5;
sum2 = mysum(a,2);``````
``````% Call 'mycomparer', passing three variables
i = 7; j = 5; k = 9;
[minValue1,maxValue1] = mycomparer(i,j,k);``````
``````% Call 'mycomparer', passing an incorrect number of inputs
[minValue2,maxValue2] = mycomparer(9,10);``````

Note that the advantage of functions is that the caller just need to know what a function does, but not how. This principle is known as “encapsulation”.

I recommend the following books to learn more on functions in MATLAB.

1. This book was the winner of a Textbook Excellence Award. The sixth chapter covers user-defined functions, scope of variables, debugging, and other aspects related to the development of MATLAB programs.

2. MATLAB for Engineers (5th Edition)

This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. Chapter 6 explains how to create and call functions.

I also recommend the other tutorials in this series.

## Source code

I hope you have learned how to call functions in MATLAB. The source code developed in this tutorial is available at this page.