Section 6 User-Defined Functions
Section 6 User-Defined Functions
USER-DEFINED FUNCTIONS
ENGR 112 – Introduction to Engineering Computing
User-Defined Functions
2
Add a directory to
your path for
frequently-used
functions, e.g.,
C:\Users\Documents\MATLAB\
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
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
Main function
Sub-function 1
Sub-function 2
@ 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
Output:
Mean value of 𝑦𝑦 = 𝑓𝑓(𝑥𝑥)
K. Webb ENGR 112
28 Recursion
1 𝑛𝑛 = 1
𝑛𝑛! = �
𝑛𝑛 ∗ 𝑛𝑛 − 1 ! 𝑛𝑛 > 1
1 𝑥𝑥 = 1
𝑛𝑛! = �
𝑥𝑥 ∗ 𝑥𝑥 − 1 ! 𝑥𝑥 > 1
𝑖𝑖𝑙𝑙𝑙𝑙𝑙𝑙 + 𝑖𝑖ℎ𝑖𝑖𝑖𝑖𝑖
𝑖𝑖𝑚𝑚𝑚𝑚𝑚𝑚 = floor
2
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