Professional Documents
Culture Documents
Functions
Introduction to Functions
Most computer programs that solve real-world problems are much larger than the programs presented in
the course so far. Experience has shown that the best way to develop and maintain a large program is to
construct it from small, simple pieces, or components. This technique is called divide and conquer.
Functions (called methods or procedures or sub-routines in other programming languages) allow the
programmer to modularize a program by separating its tasks into self-contained units. There are several
motivations for modularizing a program with functions. One is the divide-and-conquer approach, which
makes program development more manageable by constructing programs from small, simple pieces.
Another is software reusability using existing functions as building blocks to create new programs.
You have used functions in every program you have written. MATLAB programs are typically written by
combining user-defined functions the programmer writes with "prepackaged or built-in" functions in
the MATLAB Toolboxes (Library).
A function is invoked by a function call, and when the called function completes its task, it either returns a
result or simply returns control to the caller. An analogy to this program structure is the hierarchical form
of management. A boss (similar to the calling function) asks a worker (similar to the called function) to
perform a task and report back (i.e., return) the results after completing the task. The boss function does
not know how the worker function performs its designated tasks. The worker may also call other worker
functions, unbeknownst to the boss. This hiding of implementation details promotes good software
engineering. The figure below shows the boss function communicating with several worker functions in a
hierarchical manner. The boss function divides the responsibilities among the various worker functions.
Note that worker1 acts as a "boss function" to worker4 and worker5
rem()
abs()
fix()
round()
sqrt()
sin()
cos()
exp()
log()
log10()
length()
size()
Arithmetic
Status
Miscellaneous
sum()
mean()
sort()
clock()
date()
User-defined functions
You can define your own functions, using the MATLAB EDITOR, to complement the many functions
provided by MATLAB. Functions are the building blocks of your own programs. You should always try
and divide your programming task into separate functions, then design, code and test each one
independently. It is common to design from the top down, but build from the bottom up.
It is good practice to store each function in its own source file, with the name of the source file matching
the function name. Thus a function called myfunc will be stored in the file myfunc.m. This way, both
you and MATLAB can easily find the source file for a function given its name. Here is an example of a
function definition.
Example 6.1:
Define a function in a file named average.m that accepts an input vector, calculates the average of
the values, and returns a single result.
function y = average(x)
if ~isvector(x)
error('Input must be a vector')
end
y = sum(x)/length(x);
end
The first executable line of any function source file is the function declaration statement line, which has
the following format:
function output arguments = function_name(input arguments);
function keyword
(required)
Output arguments
(optional)
If your function returns more than one output, enclose the output names in square
brackets, such as
function [output1,output2,output3] = myfunction(x)
If there is no output, either omit it,
function myfunction(x)
or use empty square brackets:
function
Function name
(required)
[] = myfunction(x)
Valid function names follow the same rules as variable names. They must start with a
letter, and can contain letters, digits, or underscores. . It is also a good idea to avoid
names that MATLAB is already using.
Note: To avoid confusion, use the same name for both the file and the first function within
the file. MATLAB associates your program with the file name, not the function name.
4
Input arguments
(optional)
If your function accepts any inputs, enclose their names in parentheses after the function
name. Separate inputs with commas, such as
function y = myfunction(input1,input2,input3)
If there are no inputs, you can omit the parentheses.
Function body
(recommended)
The code between the function declaration statement and the final end keyword
constitutes the body of the function.
if ~isvector(x)
error('Input must be a vector')
end
y = sum(x)/length(x);
end
The body of a function can include valid MATLAB expressions, control flow statements,
comments, blank lines, and nested functions. The body of your function should normally
perform some computation based on the input arguments and end by assigning some
values to the output arguments.
Function end
(end keyword is
optional)
You can declare multiple local functions within the same file, or nest functions. If any
function in a file contains a nested function, all functions in the file must use the end
keyword to indicate the end of the function. Otherwise, the end keyword is optional.
As soon as we are finished defining the function, we can run/execute that function by calling the function
from the command line.
Example 6.2:
v = 1:99;
average(v)
ans =
50
5
your program and inside a function without having to pass the variable as a function argument. Here is
an example:
Example 6.3:
function initialisetable(num)
% initialise global variable TABLE to all the same value
global TABLE;
TABLE=num*ones(size(TABLE));
% main program in command window
global TABLE;
TABLE=zeros(1,100);
initialisetable(5);
Persistent Variables
Persistent variables represent a compromise between the local variable and the global variable. The
keyword persistent defines variables that are local to the function in which they are declared; yet
their values are retained in memory between calls to the function. Persistent variables are similar to global
variables because the MATLAB software creates permanent storage for both. They differ from global
variables in that persistent variables are known only to the function in which they are declared. This
prevents persistent variables from being changed by other functions or from the MATLAB command line.
and
nargout contains the number of input arguments and output arguments respectively, that are actually
supplied in the function call. This example shows how to determine how many input or output arguments
your function receives using nargin.
Example 6.4:
Input Arguments
Create a function in a file named add2_1.m that accepts up to two inputs. Identify the number of inputs
with nargin.
function c = add2_1(a,b)
You can call add2_1 with one, two, or zero input arguments.
switch nargin
case 2
6
Example 6.5:
add2_1(42)
ans =
84
add2_1(2,4000)
ans =
4002
add2_1
ans =
0
This example shows how to determine how many input or output arguments your function receives
using nargout.
Example 6.6:
Output Arguments
Create a new function in a file named add2_2.m that can return one or two outputs (a result and its
absolute value). Identify the number of requested outputs with nargout.
switch nargin
case 2
result = a + b;
-11
absValue =
11
Functions return outputs in the order they are declared in the function definition.
8
Variable-length input argument list using varargin
varargin is an input variable in a function definition statement that allows the function to accept any
number of input arguments. Specify varargin using lowercase characters, and include it as the last
input argument after any explicitly declared inputs. When the function executes, varargin is a 1-byN cell array, where N is the number of inputs that the function receives after the explicitly declared inputs.
Example 6.8:
Define a function in a file named varlist.m that accepts a variable number of inputs and displays
the values of each input.
Example 6.9:
varlist(ones(3),'some text',pi)
Number of arguments: 3
varargin{1} =
1
1
1
1
1
1
1
1
1
varargin{2} =
some text
varargin{3} =
3.1416
Recursive functions
The programs we have discussed are generally structured as functions that call one another in a
disciplined, hierarchical manner. For some problems, it is useful to have functions call themselves. A
function that calls itself, either directly or indirectly (through another function) is called a recursive
function.
The function actually knows how to solve only the simplest case(s), or so-called base case(s). If the
function is called with a base case, the function simply returns a result. If the function is called with a more
complex problem, the function typically calls itself until it reduces to its base case. This is referred to as a
9
recursive call and is also called the recursion step. The recursion step executes while the original call
to the function is still open, i.e., it has not yet finished executing. The recursion step can result in many
more such recursive calls, as the function keeps reducing each new sub-problem.
A recursive definition of the factorial function is arrived at by observing the following relationship:
n! = n ( n-1)!
For example, 5! is clearly equal to 5 * 4! as is shown by the following:
5! = 5 4 3 2 1
5! = 5 (4 3 2 1)
5! = 5 (4!)
The evaluation of 5! would proceed as shown in Figure 6.1. Figure 6.1(a) shows how the succession of
recursive calls proceeds until 1! is evaluated to be 1, which terminates the recursion. Figure 6.1(b) shows
the values returned from each recursive call to its caller until the final value is calculated and returned.
Figure 6.1. Recursive evaluation of 5!.
10
Example Using Recursion: Fibonacci Series
begins with 0 and 1 and has the property that each subsequent Fibonacci number is the sum of
the previous two Fibonacci numbers. The Fibonacci series can be defined recursively as follows:
fibonacci(0) = 0
fibonacci(1) = 1
fibonacci(n) = fibonacci(n-1) + fibonacci(n-2)
The program below calculates the nth Fibonacci number recursively by using function
fibonacci.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
1
2
3
4
5
6
7
8
9
if ( (
fib
else %
fib
end
return
values
%d,fibonacci( 20 ));
%d,fibonacci( 30 ));
%d,fibonacci( 35 ));
11
Exercises
For these exercises, use the editor window to enter your code, and save your answers to files. To
run functions, call them by name from the command window.
1. Write a function called FtoC (ftoc.m) to convert Fahrenheit temperatures into Celsius.
Make sure the program has a title comment and a help page. Test from the command
window with:
FtoC(96)
lookfor Fahrenheit
help FtoC
2. Write a function (roll2dice.m) to roll 2 dice, returning two individual variables: d1 and
d2. For example:
[d1 d2] = roll2dice
d1 =
4
d2=
3
3. Write a function (sinewave.m) to return a sine wave of a given frequency, duration and
sample rate. Replay it to check. For example:
s = sinewave(1000,0.5,11025);
sound(s,11025);
4. (Recursive Greatest Common Divisor) The greatest common divisor of integers x and y is
the largest integer that evenly divides both x and y. Write a recursive function gcd that
returns the greatest common divisor of x and y, defined recursively as follows: If y is
equal to 0, then gcd( x, y ) is x; otherwise, gcd( x, y ) is gcd( y, mod(x, y) ),
where mod is the built-in modulus function. [Note: For this algorithm, x must be larger
than y.]
5. (Advanced) Zeller's Congruence is a formula that calculates the day of the week given
the date (within a limited range of years). The formula is:
day = 1 + ([2.6m - 0.2] + d + y + [y/4] + [c/4] - 2c) modulo 7
where the square brackets mean take the integer part, modulo 7 means the remainder
when divided by 7, and
d = day of the month (e.g. 1 to 31)
m = month number with March=1, ..., December=10, January=11,
February=12. Assign January and February to previous year.
c = century number (e.g. 19)
y = year in century (e.g. 97), but remember January and February
The result is the day of the week, with 1=Sunday. Write a function dayofweek
(dayofweek.m) which takes a vector of three numbers representing the day, month and
year in conventional notation, and returns a string containing the name of the day of the
week. For example (attack on Pearl Harbour):
dayofweek([7 12 1941])
ans = Sunday
12
More Practice
1. Create a vector of the even whole numbers between 31 and 75.
2. Let x = [2 5 1 6].
a.
b.
c.
d.
4. Evaluate the following MATLAB expressions by hand and use MATLAB to check
the answers
a.
b.
c.
d.
e.
f.
g.
h.
2 / 2 * 3
6 - 2 / 5 + 7 ^ 2 - 1
10 / 2 \ 5 - 3 + 2 * 4
3 ^ 2 / 4
3 ^ 2 ^ 2
2 + round(6 / 9 + 3 * 2) / 2 - 3
2 + floor(6 / 9 + 3 * 2) / 2 - 3
2 + ceil(6 / 9 + 3 * 2) / 2 - 3
2, 4, 6, 8, ...
10, 8, 6, 4, 2, 0, -2, -4
1, 1/2, 1/3, 1/4, 1/5, ...
0, 1/2, 2/3, 3/4, 4/5, ...
13
7. Write down the MATLAB expression(s) that will
a. ... compute the length of the hypotenuse of a right triangle given
the lengths of the sides (try to do this for a vector of side-length
values).
b. ... compute the length of the third side of a triangle given the
lengths of the other two sides, given the cosine rule
c2 = a2 + b2 - 2(a)(b)cos(t)
where t is the included angle between the given sides.
8. Given a vector, t, of length n, write down the MATLAB expressions
that will correctly compute the following:
a.
b.
c.
d.
e.
f.
ln(2 + t + t2)
et(1 + cos(3t))
cos2(t) + sin2(t)
tan-1(1) (this is the inverse tangent function)
cot(t)
sec2(t) + cot(t) - 1
14
12. Plot the expression (determined in modelling the growth of the US
population)
P(t) = 197,273,000/(1 + e-0.0313(t
- 1913.25)
What
x(3)
x(1:7)
x(1:end)
x(1:end-1)
x(6:-2:1)
x([1 6 2 1 1])
sum(x)
(NB. the standard error of the mean is defined as the standard deviation
divided by the square root of the number of elements used to compute the
mean.)
15. Given the arrays x = [1 4 8], y = [2 1 5] and A = [3 1 6 ; 5 2 7],
determine which of the following statements will correctly execute and provide
the result. If the command will not correctly execute, state why it will not.
Using the command whos may be helpful here.
a.
b.
c.
d.
e.
f.
g.
x + y
x + A
x' + y
A - [x' y']
[x ; y']
[x ; y]
A - 3
A'
A(:,[1 4])
A([2 3],[3 1])
reshape(A,2,6)
A(:)
flipud(A)
fliplr(A)
[A A(end,:)]
A(1:3,:)
[A ; A(1:2,:)]
sum(A)
sum(A')
sum(A,2)
15
k. [ [ A ; sum(A) ] [ sum(A,2) ; sum(A(:)) ] ]
17. Given the array A from problem 4, above, provide the command that will
a.
b.
c.
d.
e.
x > y
y < x
x == y
x <= y
y >= x
x | y
x & y
x & (~y)
(x > y) | (y < x)
(x > y) & (y < x)
20. The exercises here show the techniques of logical-indexing (indexing with
0-1 vectors). Given x = 1:10 and y = [3 1 5 6 8 2 9 4 7 0], execute and
interpret the results of the following commands:
a.
b.
c.
d.
e.
f.
16
21. The introduction of the logical data type in v5.3 has forced some changes
in the use of non-logical 0-1 vectors as indices for subscripting. You can
see the differences by executing the following commands that attempt to
extract the elements of y that correspond to either the odd (a.) or even (b.)
elements of x:
a. y(rem(x,2)) vs.
b. y(~rem(x,2)) vs.
y(logical(rem(x,2)))
y(~logical(rem(x,2)))
...
...
...
...
if x < 6
if 6 <= x < 20
if 20 <= x <= 35
You can check your answer by plotting y vs. x with symbols. The curve should
be a triangular shape, always above zero and with a maximum of 16. It might
also be useful to try setting x to 1:35. Using multiple steps (or a simple
Mfile) is recommended for this problem.