This lecture explains the concept of functions in programming, in particular in MATLAB.

## Lecture Videos

This video is created solely as reference for the attendants of ICP2017F course at UT Austin. If you did not attend this class, then you may not find this video useful.

## Functions

Functions in programming languages are self-contained modules of code that accomplish a specific task. They usually (but not always) take some data as input, process the input data, and return a result. Therefore, the definition of function in programming goes far beyond the mathematical definition of function. For example, programming functions can have no input or output.

The main reason for writing functions is to reduce coding redundancy and increase code reuse. Once a function is written, it can be used over and over and over again. Whenever a function is needed, it can be called from the inside of the main program or from inside of other functions.

In MATLAB, like most other programming languages, function is a collection of programming statements that can be executed whenever and wherever requested. Both MATLAB scripts and functions allow you to reuse sequences of commands by storing them in program files. Scripts are the simplest type of program, since they store commands exactly as you would type them at the command line. Functions provide more flexibility, primarily because you can pass input values and return output values. The general syntax for a MATLAB function is the following,

function [y1,...,yN] = myfunc(x1,...,xM)
% here is the body of function


The above declares a function named myfunc that accepts inputs x1,...,xM and returns outputs y1,...,yN. This declaration statement must be the first executable line of the function. Just like MATLAB variables, valid function names begin with an alphabetic character, and can contain letters, numbers, or underscores.

• In a function file which contains only function definitions. The name of the file should match the name of the first function in the file.
• In a script file which contains commands and function definitions. Functions must be at the end of the file. This may seem a bit odd to you, if you already know other programming languages, for example, Python. Script files cannot have the same name as a function in the file. Functions in scripts are supported only in MATLAB R2016b or later.

Files can include multiple local functions or nested functions. For readability, use the optional end keyword to indicate the end of each function in a file. The end keyword is required when:

• Any function in the file contains a nested function.
• The function is a local function within a function file, and any local function in the file uses the end keyword.
• The function is a local function within a script file.

In general, it is always good to add the end keyword to all functions, for better readability.

Example:
Let’s write a MATLAB function that takes in a temperature value in Centigrads and converts it to Fahrenheit.

function [F] = c2f(C)
F = (9.0/5)*C + 32;
end

c_temp = 70.7; % The hottest place on Earth, Lut Desert in Iran
f_temp = c2f(c_temp);
disp(['Temperature in Fahrenheit: ',num2str(f_temp)])
disp( ['The hottest place on Earth as of 2005 is in the Lut Desert in Iran at ' ...
, num2str(70.7) ...
, ' degrees Celsius.',char(10) ...
, 'This corresponds to a temperature of ', num2str(159.26), ' degrees Fahrenheits!' ...
] );

Temperature in Fahrenheit: 159.26
The hottest place on Earth as of 2005 is in the Lut Desert in Iran at 70.7 degrees Celsius.
This corresponds to a temperature of 159.26 degrees Fahrenheits!


### Functions with no input arguments

We can define functions that take no input argument, yet do something predefined for us. Consider the following function which gives information about the ICP course, when called.

function info = get_ICP_info()
info = 'ASE/COE 301: Introduction to Computer Programming (ICP) is a 3-hours credit course offered as part of the undergraduate coursework in the Aerospace and the Computational Engineering programs at The University of Texas at Austin.';
end

>> out = get_ICP_info()

ASE/COE 301: Introduction to Computer Programming (ICP) is a 3-hours credit course offered as part of the undergraduate coursework in the Aerospace and the Computational Engineering programs at The University of Texas at Austin.


### Functions with no output (return value)

We can also modify the above function such that it does not return anything specifically.

function get_ICP_info()
disp('ASE/COE 301: Introduction to Computer Programming (ICP) is a 3-hours credit course offered as part of the undergraduate coursework in the Aerospace and the Computational Engineering programs at The University of Texas at Austin.');
end

>> get_ICP_info()

ASE/COE 301: Introduction to Computer Programming (ICP) is a 3-hours credit course offered as part of the undergraduate coursework in the Aerospace and the Computational Engineering programs at The University of Texas at Austin.


This is almost equivalent to the word void in languages like Java, C, and C++. If you set a variable equal to this function, you will get an error message, because the function does not return anything as output.

>> out = get_ICP_info()
Error using get_ICP_info
Too many output arguments.


### Functions with multiple input arguments

Functions can take almost as many input arguments as we wish. Consider the following that takes two arguments,

function result = mypower(base,exponent)
result = base^exponent;
return
end

>> mypower(10,2)
ans =
100


#### Variable number of input arguments

The functions that we have written thus far have contained a fixed number of input arguments and a fixed number of output arguments. But you can also define a MATLAB function that accepts a variable number of inputs. In this case you use MATLAB’s builtin input argument cell varargin in place of the arbitrary number of input arguments. The function nargin returns the number of input arguments that were passed to the function. For example, consider the following function that displays the values of each input to the function,

function varlist(year,varargin)
fprintf('Number of arguments: %d\n',nargin)
celldisp(varargin)
fprintf('The year is %d\n',year)
fprintf('type of varargin is %s\n',class(varargin))
end

>> varlist(2017,'what','a ','nice', 'weather')
Number of arguments: 5
varargin{1} =
what
varargin{2} =
a
varargin{3} =
nice
varargin{4} =
weather
The year is 2017
type of varargin is cell


#### Optional arguments using inputParser

Unlike other languages such as Python, Fortran and C++, there is no simple direct way of having optional arguments in MATLAB functions, other than the one described above, using varargin. However, MATLAB has a powerful set of built-in capabilities known as inputParser for parsing the input arguments of a given function. The usage and details of this method goes beyond the scope of this class. However, you can learn more about it here.

### Functions with multiple output (return values)

MATLAB functions can also return more than one output value. The output could be of any type: vector, matrix, cell, structure, etc. For example, consider a function that takes an input vector of double and calculates its mean and standard deviation.

function [m,s] = stat(x)  % a function that returns the result as vector of length two
n = length(x);
m = sum(x)/n;
s = sqrt(sum((x-m).^2/n));
end

>> values = [12.7, 45.4, 98.9, 26.6, 53.1];
>> stat(values)
ans =
47.3400


Notice that if you don’t provide two output arguments, then basically only one is reported.

>> valuesMean = stat(values)
valuesMean =
47.3400

>> [valuesMean, valuesStd] = stat(values)
valuesMean =
47.3400
valuesStd =
29.4124

>> [valuesMean, valuesStd, dummy] = stat(values)   % too many output arguments is meaningless
Error using stat
Too many output arguments.

function [x,result] = stat(x) % the same function as above, but now returning the result as a structure, together with input x
result = struct();
result.n = length(x);
result.mean = sum(x) / result.n;
result.std = sqrt( sum( (x-result.mean).^2 / result.n ) );
end

>> values = [12.7, 45.4, 98.9, 26.6, 53.1];
>> stat(values)
ans =
12.7000   45.4000   98.9000   26.6000   53.1000

>> [input,ouput] = stat(values)
input =
12.7000   45.4000   98.9000   26.6000   53.1000
ouput =
n: 5
mean: 47.3400
std: 29.4124


Exercise
Write a function that takes in three coefficients $(a,b,c)$ of a quadratic equation $ax^2+bx+c$ and finds the roots of this equation.

function [x1,x2] = quadform(a,b,c)
d = sqrt(b^2 - 4*a*c);
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end

>> [r1,r2] = quadform(1,1,1)
r1 =
-0.5000 + 0.8660i
r2 =
-0.5000 - 0.8660i


#### Variable number of output arguments

A variable number of output arguments can also be specified. For example, consider the following function typesize() which takes one input argument inputval. The function will always return a character specifying whether the input argument was a scalar (‘s’), vector (‘v’), or matrix (‘m’). This character is returned through the output argument arrtype. Additionally, if the input argument was a vector, the function also returns the length of the vector, and if the input argument was a matrix, the function returns the number of rows and the number of columns of the matrix. The MATLAB’s builtin output argument varargout is used, which is a cell array. So, for a vector the length is returned through varargout, and for a matrix both the number of rows and columns are returned through varargout,

function [arrtype, varargout] = typesize(inputval)
% typesize returns a character 'scalar' for scalar, 'vector'
% for vector, or 'matrix' for matrix input argument
% also returns length of a vector or dimensions of matrix
% Format: typesize(inputArgument)
[nrow, ncol ] = size(inputval);
if nrow==1 && ncol==1
arrtype = 'scalar';
elseif nrow==1 || ncol==1
arrtype = 'vector';
varargout{1} = length(inputval);
else
arrtype = 'matrix';
varargout{1} = nrow;
varargout{2} = ncol;
end
end

>> typesize(10)
ans =
scalar
>> typesize(10:12)
ans =
vector
>> [inputType,inputLength] = typesize(10:12)
inputType =
vector
inputLength =
3
>> [inputType,nrow,ncol] = typesize([10:12;13:15])
inputType =
matrix
nrow =
2
ncol =
3