You are on page 1of 16

1

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

A Few Built-in MATLAB Functions


Generation
zeros()
ones()
rand()

Matrix of specified size filled with zeros


Matrix of specified size filled with ones
generate pseudo random number(s) between 0 and 1

rem()
abs()
fix()
round()
sqrt()
sin()
cos()
exp()
log()
log10()

remainder after integer division


absolute value (also character -> number)
truncate a value to its integer part (towards zero)
round a value to nearest integer.
Square root
sine (angle in radians)
Cosine (angle in radians)
Exponential
natural logarithm
Logarithm base 10

length()
size()

length of a vector (longest dimension of matrix)


size of a matrix [nrows, ncols]

Arithmetic

Status

Miscellaneous
sum()
mean()
sort()
clock()
date()

sum the elements of a vector


find mean of elements of a vector
sort the elements of a vector in increasing size
returns date and time as a vector [year month day hour minute seconds]
Returns date as a string dd-mmm-yyyy

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

Use lowercase characters for the 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)

%define vector of values from 1 to 99


%call to user-defined function average to give result

ans =
50

Local vs Global Variables


Both lists of input and output arguments in the function declaration statement are visible only within the
function in which they are declared and are therefore local to that function. Consequently, they are called
local variables. Variables defined within the body of the function are also local variables. It is good
practice to pass all the information you need for a function through the list of input arguments and to
retrieve all the processed results via the output arguments. Although this requires a lot of copying,
MATLAB does this quite efficiently.
Sometimes however, you may have a number of functions that all require access to the same table of
data, and you dont want to keep copying the table into the function and then copying the changes back
into your program. Imagine if the table had a million elements! Under these circumstances you can
declare variables as global variables. This means that the table of data can be accessed both inside

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.

Varying the Number of Input and Output Arguments


You can also write functions which take a variable number of arguments. In fact MATLAB allows any
function to be called with fewer arguments than specified in the definition of the function, so it is a good
idea to always check the number of arguments supplied at run time. The built in variables nargin

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.

function [result,absResult] = add2_2(a,b)

switch nargin
case 2
result = a + b;

You can call add2_2 with one or two output arguments.


Example 6.7:
value = add2_2(11,-22)
value =
-11
[value,absValue] = add2_2(11,-22)
value =

-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:

Variable Number of Function Inputs

Define a function in a file named varlist.m that accepts a variable number of inputs and displays
the values of each input.

Call varlist with several inputs and view result.

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

The Fibonacci series


0, 1, 1, 2, 3, 5, 8, 13, 21, ...

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

% main program located in file main.m


% Testing the recursive fibonacci function.

1
2
3
4
5
6
7
8
9

% recursive method Fibonacci located in file fibonacci.m


function fib = fibonacci( number )

% calculate the fibonacci values of 0 through 10


for counter = 0:10
fprintf(fibonacci( %d ) = %d,counter,fibonacci( counter ));
end
% display higher fibonacci
fprintf(fibonacci( 20 ) =
fprintf(fibonacci( 30 ) =
fprintf(fibonacci( 35 ) =
% end main program

if ( (
fib
else %
fib
end
return

values
%d,fibonacci( 20 ));
%d,fibonacci( 30 ));
%d,fibonacci( 35 ));

number == 0 ) || ( number == 1 ) ) % base cases


= number;
recursion step
= fibonacci( number - 1 ) + fibonacci( number - 2 );
% end function fibonacci

Reading "Getting Started: Scripts and Functions" in MATLAB Help.

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

6. (Homework) A musical semitone is a frequency interval corresponding to the twelfth root


of 2 (i.e. 2^(1/12)). We can number semitones with respect to the 'A' above middle C
which has the frequency 440Hz, i.e. semitone 0 = 440Hz, semitone 1 = 466.2Hz, etc.
Write a program which plays the Westminster chimes, with
tones=[ 0 4 2 9 9 2 0 4 ];

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.

Add 16 to each element


Add 3 to just the odd-index elements
Compute the square root of each element
Compute the square of each element

3. Let x = [3 2 6 8]' and y = [4 1 3 5]' (NB. x and y should be column


vectors).
a. Add the sum of the elements in x to y
b. Raise each element of x to the power specified by the corresponding element
in y.
c. Divide each element of y by the corresponding element in x
d. Multiply each element in x by the corresponding element in y, calling the
result "z".
e. Add up the elements in z and assign the result to a variable called "w".
f. Compute x'*y - w and interpret the result

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

5. Create a vector x with the elements ...


a.
b.
c.
d.

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, ...

6. Create a vector x with the elements,


xn = (-1)n+1/(2n-1)
Add up the elements of the version of this vector that has 100 elements.

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

Test that your solution works for t = 1:0.2:2


9. Plot the functions x, x3, ex and ex2 over the interval 0 < x < 4 ...
a. on rectangular paper
b. on semilog paper (logarithm on the y-axis)
c. on log-log paper
Be sure to use an appropriate mesh of x values to get a smooth set
of curves.
10. Make a good plot (i.e., a non-choppy plot) of the function
f(x) = sin(1/x)
for 0.01 < x < 0.1.
good?

How did you create x so that the plot looked

11. In polar coordinates (r,t), the equation of an ellipse with one of


its foci at the origin is
r(t) = a(1 - e2)/(1 - (e)cos(t))
where a is the size of the semi-major axis (along the x-axis) and
e is the eccentricity. Plot ellipses using this formula, ensuring
that the curves are smooth by selecting an appropriate number of
points in the angular (t) coordinate. Use the command axis equal to
set the proper axis ratio to see the ellipses.

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)

where t is the date, in years AD, using t = 1790 to 2000.


population is predicted in the year 2020?

What

13. Given x = [3 1 5 7 9 2 6], explain what the following commands "mean" by


summarizing the net result of the command.
a.
b.
c.
d.
e.
f.
g.

x(3)
x(1:7)
x(1:end)
x(1:end-1)
x(6:-2:1)
x([1 6 2 1 1])
sum(x)

14. Given the array A = [2 4 1; 6 7 2; 3 5 9], provide the commands needed to


a.
b.
c.
d.
e.

assign the first row of A to a vector called x1


assign the last 2 rows of A to an array called y
compute the sum over the columns of A
compute the sum over the rows of A
compute the standard error of the mean of each column of A

(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

16. Given the array A = [2 7 9 7 ; 3 1 5 6 ; 8 1 2 5], explain the results of


the following commands:
a.
b.
c.
d.
e.
f.
g.
h.
i.
j.
k.
l.
m.

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.

assign the even-numbered columns of A to an array called B


assign the odd-numbered rows to an array called C
convert A into a 4-by-3 array
compute the reciprocal of each element of A
compute the square-root of each element of A

18. Give the following commands to create an array called F:


>> randn('seed',123456789)
>> F = randn(5,10);
a. Compute the mean of each column and assign the results to the elements of a
vector called avg.
b. Compute the standard deviation of each column and assign the results to the
elements of a vector called s.
c. Compute the vector of t-scores that test the hypothesis that the mean of
each column is no different from zero.
d. If Pr(|t| > 2.132 ) = 0.1 with 4 degrees of freedom, are any of the mean
values in the vector avg statistically different from 0?
19. Given that x = [1 5 2 8 9 0 1] and y = [5 2 2 6 0 0 2], execute and
explain the results of the following commands:
a.
b.
c.
d.
e.
f.
g.
h.
i.
j.

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.

(x > 3) & (x < 8)


x(x > 5)
y(x <= 4)
x( (x < 2) | (x >= 8) )
y( (x < 2) | (x >= 8) )
x(y < 0)

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)))

22. Given x = [3 15 9 12 -1 0 -12 9 6 1], provide the command(s) that will


a.
b.
c.
d.

...
...
...
...

set the values of x that are positive to zero


set values that are multiples of 3 to 3 (rem will help here)
multiply the values of x that are even by 5
extract the values of x that are greater than 10 into a vector
called y
e. ... set the values in x that are less than the mean to zero
f. ... set the values in x that are above the mean to their
difference from the mean
23. Create the vector x = randperm(35) and then evaluate the following
function using only logical indexing:
y(x) = 2
= x - 4
= 36 - x

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.

You might also like