SECTION 6:
USER-DEFINED FUNCTIONS
ENGR 112 – Introduction to Engineering Computing
User-Defined Functions
2
By now you’re accustomed to using built-in MATLAB
functions in your m-files
Consider, for example, mean.m
Commonly-used function
Need not write code each time an average is calculated
An m-file – written using other MATLAB functions
Functions allow reuse of commonly-used blocks of code
Executable from any m-file or the command line
Can create user-defined functions as well
Just like built-in functions – similar syntax, structure,
reusability, etc.
K. Webb ENGR 112
User-Defined Functions
3
Functions are a specific type of m-file
Function m-files start with the word function
Can accept input arguments and return outputs
Useful for tasks that must be performed repeatedly
Functions can be called from the command line, from
within m-files, or from within other functions
Variables within a function are local in scope
Internal variables – not outputs – are not saved to the
workspace after execution
Workspace variables not available inside a function, unless
passed in as input arguments
K. Webb ENGR 112
Anatomy of a Function
4
Function m-file must
begin with the word Function Input
‘function’ Output(s) Argument(s)
Name
Help comments –
displayed when help is
requested at the
command line:
MATLAB commands that
define the function
Terminate the function Always comment your code
with the word ‘end’
K. Webb ENGR 112
Commenting Functions
5
Any function – built-in or user-defined – is accessible by
the command-line help system
Type: help functionName
Help text that appears is the first comment block
following the function declaration in the function m-file
Make this comment block particularly descriptive and
detailed
Comments are particularly important for functions
Often reused long after they are written
Often used by other users
K. Webb ENGR 112
M-Files vs. Functions
6
Most code you write in MATLAB can be written as
regular (non-function) m-files
Functions are most useful for frequently-repeated
operations
M-Files Functions
Scope of variables Global Local
Facilitates debugging Use debugger to access
internal function variables
Inputs/Outputs No Yes
All variables in memory at the
time of execution are
available. All variables remain
in the workspace following
execution.
Reuse Yes Yes
Help contents No Yes
K. Webb ENGR 112
The MATLAB Path
7
All functions outside of the PWD – user-defined or
built-in – must be in the path to be accessed
Add a directory to
your path for
frequently-used
functions, e.g.,
C:\Users\Documents\MATLAB\
K. Webb ENGR 112
Function Inputs and Outputs
8
function y = func(x)
Here, x is the input passed to the function func
Passed to the function from the calling m-file
Not defined within the function
y is the output returned from the function
Defined within the function
Passed out to the calling m-file
Theonly function variable available upon return from the
function call
K. Webb ENGR 112
Multiple Inputs and Outputs
9
function [y1,y2] = func(x1,x2,x3)
Functions may have more than one input and/or
output
Here, three inputs: x1, x2, and x3
and two outputs: y1 and y2
Inputsseparated by commas
Outputs enclosed in square brackets and separated by
commas
K. Webb ENGR 112
Function – Example
10
Consider a function that converts a distance in kilometers to a
distance in both miles and feet
One input, two outputs
K. Webb ENGR 112
11 Optional Input Arguments
K. Webb ENGR 112
Optional Input Arguments
12
Functions often have optional input arguments
Variable number of input arguments may be required when
calling the function
Optional inputs may have default values
Function behavior may differ depending on what inputs are
specified
For example, MATLAB’s mean.m function:
y = mean(x)
Optionally, specify the dimension along which to calculate
mean values:
y = mean(x,dim)
K. Webb ENGR 112
Optional Input Arguments
13
mean.m allows you to
specify the dimension
along which the mean is
calculated
Default is dim = 1
If dim is not specified, it
is set to 1 within the
function
Calculate mean values of
columns
Setting dim = 2
calculates mean values
of rows
K. Webb ENGR 112
Optional Input Arguments
14
Just like built-in functions, user-defined functions
can also have optional inputs
Code executed when function is called depends on
the number of input arguments
nargin.m returns the number of input arguments
passed to a function
Allows for checking how many input arguments were
specified
Use conditional statements to control code branching
If an input was not specified, set it to a default value
K. Webb ENGR 112
Optional Inputs – Example 1
15
For example,
consider a function
designed to return a
vector of values
between xi and xf
Third input
argument, N, the
number of elements
in the output vector,
is optional
Default is N = 10
K. Webb ENGR 112
Optional Input Arguments
16
Sometimes we want to allow for optional inputs in
the middle, not at the end, of the input list
For example, maybe the second of three inputs is
optional (or the second and third inputs)
nargin.m alone won’t work here
Can’t differentiate between skipping the second of
three inputs or the third of three inputs
nargin == 2 in both cases
Instead of skipping the input altogether, pass an
empty set, [ ], in its place
K. Webb ENGR 112
Optional Inputs – Example 2
17
Revisit the same vector-
generating function
Now both the first
input, xi, and the third
input, N, are optional
If xi is not specified it
defaults to xi = 0
Single input, intended
to be xf, is assumed to
be xi, the first listed
input argument
Must assign the single
input argument to xf
K. Webb ENGR 112
Error Checking Using nargin.m
18
Can use nargin.m
to provide error
checking
Ensure that the
correct number of
inputs were specified
Use error.m to
terminate execution
and display an error
message
K. Webb ENGR 112
19 Sub-Functions
K. Webb ENGR 112
Sub-Functions
20
Functions are useful for blocks of code that get
called repeatedly
We often have such blocks within functions themselves
Can define additional functions in separate m-files
Or, if the code is only useful within that specific
function, define a sub-function
Sub-Functions
A function defined within another function m-file
Local scope: only available from within that function
Organizes, simplifies overall function code
K. Webb ENGR 112
Sub-Functions – Example
21
Here, two sub-
functions are defined
and called from within
the main function
Main function
Sub-function 1
Sub-function 2
K. Webb ENGR 112
22 Anonymous Functions
K. Webb ENGR 112
Anonymous Functions
23
It is often desirable to create a function without having to
create a separate function file for it
Anonymous functions:
Can be defined within an m-file or at the command line
Function data type is function_handle
A pointer to the function
Can accept inputs, return outputs
May contain only a single MATLAB expression
Only one output
Useful for passing functions to functions
E.g. using quad.m (a built-in MATLAB function) to integrate a
mathematical function (a user-defined function)
K. Webb ENGR 112
Anonymous Functions - Syntax
24
fhandle = @(arglist) expression
@ symbol
Function definition
generates a handle A single executable
for the function MATLAB expression
E.g. x.^2+3*y;
Function name
A variable of type A list of input variables
function_handle E.g. @(x,y);
Pointer to the function Note that outputs are not
explicitly defined
K. Webb ENGR 112
Anonymous Functions – Examples
25
Simple function that returns
half of the input value
May have multiple inputs
First-ordersystem response –
inputs: time constant, value of
time
Inputs may be vectors
Outputs may be vectors as
well
K. Webb ENGR 112
Passing Functions to Functions
26
We often want to perform MATLAB functions on other
functions
E.g. integration, roots finding, optimization, solution of
differential equations – these are function functions
This is the real value of anonymous functions
Define an anonymous function
Pass the associated function
handle to the function as an
input
Here, integrate the function, f,
from 0 to 10 using MATLAB’s
quad.m function
K. Webb ENGR 112
Function Function – Example
27
Consider a function that
calculates the mean of a
mathematical function
evaluated at a vector of
independent variable
values
Inputs:
Function handle
Vector of 𝑥𝑥 values
Output:
Mean value of 𝑦𝑦 = 𝑓𝑓(𝑥𝑥)
K. Webb ENGR 112
28 Recursion
K. Webb ENGR 112
Recursive Functions
29
Recursion is a problem solving approach in which a
larger problem is solved by solving many smaller,
self-similar problems
A recursive function is one that calls itself
Each time it calls itself, it, again, calls itself
Two components to a recursive function:
A base case
A single case that can be solved without recursion
A general case
A recursive relationship, ultimately leading to the base case
K. Webb ENGR 112
Recursion Example 1 – Factorial
30
We have considered iterative algorithms for computing
𝑦𝑦 = 𝑛𝑛!
for loop, while loop
Factorial can also be computed using recursion
It can be defined with a base case and a general case:
1 𝑛𝑛 = 1
𝑛𝑛! = �
𝑛𝑛 ∗ 𝑛𝑛 − 1 ! 𝑛𝑛 > 1
The general case leads back to the base case
𝑛𝑛! defined in terms of 𝑛𝑛 − 1 !, which is, in turn, defined in terms
of 𝑛𝑛 − 2 !, and so on
Ultimately, the base case, for 𝑛𝑛 = 1, is reached
K. Webb ENGR 112
Recursion Example 1 – Factorial
31
1 𝑥𝑥 = 1
𝑛𝑛! = �
𝑥𝑥 ∗ 𝑥𝑥 − 1 ! 𝑥𝑥 > 1
The general case is a recursive relationship, because it
defines the factorial function using the factorial function
The function calls itself
In MATLAB:
K. Webb ENGR 112
Recursion Example 1 – Factorial
32
Consider, for example: 𝑦𝑦 = 4!
fact.m recursively called four
times
Fourth function call terminates first,
once the base case is reached
Function calls terminate in reverse
order
Function call doesn’t terminate until
all successive calls have terminated
K. Webb ENGR 112
Recursion Example 2 – Binary Search
33
A common search algorithm is the binary search
Similar to searching for a name in a phone book or a word in
a dictionary
Look at the middle value to determine if the search item is
in the upper or lower half
Look at the middle value of the half that contains the search
item to determine if it is in that half’s upper or lower half, …
The search function gets called recursively, each time
on half of the previous set
Search range shrinks by half on each function call
Recursion continues until the middle value is the search
item – this is the required base case
K. Webb ENGR 112
Recursion Example 2 – Binary Search
34
Recursive binary search – the basic algorithm:
Find the index, 𝑖𝑖, of 𝑥𝑥 in the sorted list, 𝐴𝐴, in the range of 𝐴𝐴 𝑖𝑖𝑙𝑙𝑙𝑙𝑙𝑙 : 𝑖𝑖ℎ𝑖𝑖𝑖𝑖𝑖
1) Calculate the middle index of 𝐴𝐴 𝑖𝑖𝑙𝑙𝑙𝑙𝑙𝑙 : 𝑖𝑖ℎ𝑖𝑖𝑖𝑖𝑖 :
𝑖𝑖𝑙𝑙𝑙𝑙𝑙𝑙 + 𝑖𝑖ℎ𝑖𝑖𝑖𝑖𝑖
𝑖𝑖𝑚𝑚𝑚𝑚𝑚𝑚 = floor
2
2) If 𝐴𝐴 𝑖𝑖𝑚𝑚𝑚𝑚𝑚𝑚 == 𝑥𝑥, then 𝑖𝑖 = 𝑖𝑖𝑚𝑚𝑚𝑚𝑚𝑚 , and we’re done
3) If 𝐴𝐴 𝑖𝑖𝑚𝑚𝑚𝑚𝑚𝑚 > 𝑥𝑥, repeat the algorithm for 𝐴𝐴 𝑖𝑖𝑙𝑙𝑙𝑙𝑙𝑙 : 𝑖𝑖𝑚𝑚𝑚𝑚𝑚𝑚 − 1
4) If 𝐴𝐴 𝑖𝑖𝑚𝑚𝑚𝑚𝑚𝑚 < 𝑥𝑥, repeat the algorithm for 𝐴𝐴 𝑖𝑖𝑚𝑚𝑚𝑚𝑚𝑚 + 1: 𝑖𝑖ℎ𝑖𝑖𝑖𝑖𝑖
K. Webb ENGR 112
Recursion Example 2 – Binary Search
35
Find the index of the 𝑥𝑥 = 9 in: 𝐴𝐴 = [0, 1, 3, 5, 6, 7, 9, 12, 16, 20]
𝐴𝐴 = [0, 1, 3, 5, 6, 7, 9, 12, 16, 20]
𝐴𝐴 𝑖𝑖𝑚𝑚𝑚𝑚𝑚𝑚 = 𝐴𝐴 6 = 7
𝐴𝐴 𝑖𝑖𝑚𝑚𝑚𝑚𝑚𝑚 = 𝐴𝐴 5 = 6 𝐴𝐴 𝑖𝑖𝑚𝑚𝑚𝑚𝑚𝑚 < 𝑥𝑥
𝐴𝐴 𝑖𝑖𝑚𝑚𝑚𝑚𝑚𝑚 < 𝑥𝑥 Start over for 𝐴𝐴 7
Start over for 𝐴𝐴 6: 10
𝐴𝐴 = [0, 1, 3, 5, 6, 7, 9, 12, 16, 20]
𝐴𝐴 = [0, 1, 3, 5, 6, 7, 9, 12, 16, 20]
𝐴𝐴 𝑖𝑖𝑚𝑚𝑚𝑚𝑚𝑚 = 𝐴𝐴 7 = 9
𝐴𝐴 𝑖𝑖𝑚𝑚𝑚𝑚𝑚𝑚 = 𝐴𝐴 8 = 12 𝐴𝐴 𝑖𝑖𝑚𝑚𝑚𝑚𝑚𝑚 == 𝑥𝑥
𝐴𝐴 𝑖𝑖𝑚𝑚𝑚𝑚𝑚𝑚 > 𝑥𝑥 𝑖𝑖 = 𝑖𝑖𝑚𝑚𝑚𝑚𝑚𝑚 = 7
Start over for 𝐴𝐴 6: 7
K. Webb ENGR 112
Recursion Example 2 – Binary Search
36
Recursive binary
search algorithm in
MATLAB
Base case for
A(imid) == x
Function is called
recursively on
successively halved
ranges until base
case is reached
K. Webb ENGR 112
Recursion Example 2 – Binary Search
37
A=[0,1,3,5,6,7,9,12,16,20]
x=9
ind = binsearch(A,x,1,10)
ind = 7
K. Webb ENGR 112