Course Book Matlab TMMI Introduction
Course Book Matlab TMMI Introduction
An Introduction
How to Use This Book
This handbook accompanies the taught sessions for the course. Each section contains
a brief overview of a topic for your reference and one or more exercises.
The document is written as a PDF, with internal links as well as links to online
documentation. Furthermore, it has been designed so that you can copy and paste
example commands from the PDF. You should have the PDF open during the taught
sessions of the course.
The Exercises
Exercises are arranged as follows:
• A title and brief overview of the tasks to be carried out
• A numbered set of tasks, together with a brief description of each
• A numbered set of detailed steps that will achieve each task
Some exercises, particularly those within the same section, assume that you have
completed earlier exercises. Your teacher will direct you to the location of files that
are needed for the exercises. If you have any problems with the text or the exercises,
please ask the teacher or demonstrator for help.
This book includes plenty of exercise activities - more than can usually be completed
during the hands-on sessions of the course. You should select some to try during the
course, while the teacher and demonstrator(s) are around to guide you. Later, you
may attend follow-up sessions at ITLP called Computer8, where you can continue
to work on the exercises, with some support from IT teachers. Other exercises are
for you to try on your own, as a reminder or an extension of the work done during
the course.
Writing Conventions
A number of conventions are used to help you to be clear about what you need to
do in each step of a task.
• In general, the word press indicates you need to press a key on the key-
board. Click, choose or select refer to using the mouse and clicking on
items on the screen.
• Names of keys on the keyboard, for example the Enter (or Return) key are
shown like this Enter.
• Multiple key names linked by a + (for example, Ctrl+Z) indicate that
the first key should be held down while the remaining keys are pressed; all
keys can then be released together.
• Words and commands typed in by the user are shown like this.
• Labels and titles on the screen are shown like this, unless there is a link to
a help file in which case they are shown as follows: help.
Software Used
MATLAB R2014a
Windows 7
Revision Information
Version Date Author Changes Made
2.0 Nov 2010 Robert Stewart Complete rewrite
2.1 Jan 2011 Robert Stewart Update
2.2 May 2011 Robert Stewart Update
2.3 Oct 2011 Robert Stewart Update
2.4 Feb 2012 Robert Stewart Update
2.5 May 2012 Robert Stewart Update
3.0 Oct 2012 Robert Stewart Major Update
3.1 Dec 2012 Robert Stewart Update
4.0 Jan 2013 Robert Stewart 4 Session Update
4.1 May 2013 Robert Stewart Exercise Updates
4.2 Jan 2014 Robert Stewart Exercise Updates
4.3 Oct 2014 Robert Stewart New Version Up-
dates
5.0 Jan 2015 Erasmia Lyka / Tasos Pa- Version Update
pastylianou
5.1 May 2015 Erasmia Lyka Exercise Updates
6.0 Oct 2015 Erasmia Lyka Exercise Updates
Copyright
This document and the accompanying presentation slides are made available by
Erasmia Lyka, under a Creative Commons licence: Attribution, Non Commercial,
No Derivatives. Individual resources are subject to their own licencing conditions
as listed.
Screenshots in this document are copyright of The Mathworks.
The Oxford University logo and crest is copyright of Oxford University and may only
be used by Oxford University members in accordance with the Universitys branding
guidelines.
3 Matrices 11
3.1 Matrix Fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.2 Matrix Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.3 Matrix Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.4 Matrix Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.5 Matrix Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.6 Matrix Resizing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.7 Matrix Reshaping and Shifting . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.8 Matrix Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
6 Programming Fundamentals 33
6.1 Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
6.2 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
6.3 Script Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
6.3.1 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
6.3.2 Housekeeping Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
6.3.3 Script Body - drawing a circle . . . . . . . . . . . . . . . . . . . . . . . . . 34
6.4 Function Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
6.4.1 Function Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
6.4.2 Help Comment Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
6.4.3 Function Body . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
9 File Handling 62
9.1 MAT-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
9.1.1 GUI Import and Export . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
9.2 Excel Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
9.3 Text (ASCII) Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
9.4 Binary Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
10 Performance 71
10.1 Measuring Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
10.1.1 Stopwatch timing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
10.1.2 The Profiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
10.2 Improving Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
10.2.1 Preallocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
10.2.2 Vectorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
11 What Next? 77
11.1 Computer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
11.2 IT Services Help Centre . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
11.3 Downloadable Course Materials and More - The ITLP Portfolio . . . . . . . . . . 77
11.4 Books . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
1 Introduction
Welcome to the course MATLAB: An Introduction
This booklet accompanies the course delivered by Oxford University’s IT Learning
Programme. Although the exercises are clearly explained so that you can work
through them yourselves, you will find that it will help if you attend the taught
session where you can get advice from the teacher, demonstrator and each other.
If at any time you are not clear about any aspect of the course, please make sure
you ask your teacher or demonstrator for some help. If you are away from the class,
you can get help by email from your teacher or from [email protected].
• Matrices
• Data Types
Session 2: MATLAB Language and Programming Fundamentals
• Operators and Control Statements
• Programming Fundamentals
Session 3: Working with Graphics
• Graphics 1: Figures, Axes and Graphics
• Performance
2.1 Overview
Figure 2.1: The MATLAB Desktop: a Java GUI with several components.
The layout can be altered using the desktop Home tab Layout button:
See also the Desktop Overview
The MATLAB Desktop is a Java GUI and, as such, should appear and behave in
a similar fashion on different operating systems. The two most important Desktop
Tools are the Command Window, which usually sits in the centre of the Desktop, and
the Editor, which usually occupies a separate window (though it may be docked).
In this session, we will introduce both.
Our command has created a variable called ans and assigned it the value 3. ans is
a special, generic variable short for answer. It is used and overwritten whenever a
statement returns a value that is not explicitly assigned to a variable.
MATLAB can perform basic arithmetic like a calculator. Entering
3+4
at the command prompt returns the value 7 in ans, overwriting the previous value.
In MATLAB + is one of a family of arithmetic operators (see section 5).
Getting Help
For help on commands and operators you can enter help followed by the com-
mand, or operator name. e.g.
help fliplr
Further information is sometimes available using doc in the same way.
doc fliplr
Each time MATLAB outputs to ans, the old value is lost. For the system to re-
member more than one thing at a time, we need to define named variables:
x = 3+4
y = 3*4
As noted above, variable values are displayed in the Command Window when the
variable name is entered. However, adding a semi-colon after a variable name, or
expression, suppresses the usual output. Compare:
x
x;
To save space in program output, we can use disp to display variable values without
printing the array name.
disp(x)
The clc command clears the Command Windows, while the home function sends
the cursor home (to the top left of the Command Window). These look superficially
similar but the Command Window history is still visible by scrolling up for home
but not clc. Paged output can be obtained using more.
The startup folder is the current folder in the MATLAB application when it
starts. On Windows and Apple Macintosh platforms, a folder called userpath is
added automatically to the search path (see below) upon startup, and is the default
startup folder. On Linux platforms, you can set the userpath as the startup folder.
You can view and edit the current user path by running userpath.
MATLABPATH
H:\My Documents\MATLAB
C:\Program Files\MATLAB\R200nn\toolbox\matlab\general
C:\Program Files\MATLAB\R200nn\toolbox\matlab\ops
C:\Program Files\MATLAB\R200nn\toolbox\matlab\lang
C:\Program Files\MATLAB\R200nn\toolbox\matlab\elmat
C:\Program Files\MATLAB\R200nn\toolbox\matlab\elfun
...
To edit the path, you can use addpath, rmpath, genpath, pathtool and savepath.
Alternatively, use the Set Path button on the Desktop Home tab (next to Layout):
The MATLAB Editor is used to view and edit MATLAB program files. Normal
MATLAB programs are text files with a .m extension and are often called M-files.
The Editor starts automatically when you create or open an M-file and provides
code highlighting and debugging features.
The simplest kind of MATLAB program is called a script. Scripts are simply a list
of commands stored in an M-file. When you run a script, the result is exactly the
same as if the commands were entered one-by-one in the command window.
To open a new (blank) script, you can use the key combination Ctrl+n, or click
the New button in the editor, or the New Script button on the desktop Home tab.
To open an existing file, you can use the edit or open commands, the key combi-
nation Ctrl+o, or click on the Open button in the editor or desktop Home tab.
Running scripts There are two main ways to run a script in MATLAB.
1. From the Command Window, you can enter the script name.
2. From the Editor, you can press F5, or click the Run button (which features
a green ’play’ triangle).
3 Matrices
• The elements of a matrix must all be of the same data type (see section
4) (numeric, character, logical etc.), but here we will focus on numeric
matrices.
• MATLAB also supports data structures that have more than two dimen-
sions. These data structures are referred to as multidimensional arrays in
the MATLAB documentation, and indeed the matrix is really a special case
of an n-dimension array, with n=2 (see section 4). In this section, we will
focus on two-dimensional matrices.
There are many ways to create a matrix in MATLAB. In section 2.3, the code
examples with defined variables created simple matrices to store scalar numeric data.
A simple way to create two-dimensional matrices is to use the matrix constructor
operator, [ ]. For example,
A = [6 3 2 8; 5 1 3 7; 1, 6, 7, 2;4,5,4,1]
A =
6 3 2 8
5 1 3 7
1 6 7 2
4 5 4 1
Each row of the matrix is terminated with a semi-colon, while the elements within
each row are separated by either commas or spaces. Spaces matter when dealing
with signed numeric data, and commas are less error-prone. Compare:
[7 -2 +5], [7 - 2 + 5], [7, - 2, +5]
Because matrices are rectangular, all rows in a matrix must have the same number
of elements and MATLAB will return an error if this condition is violated.
B = [6 3 2 8; 5 1 3]
In addition to the matrix constructor operator, MATLAB also has a number of built-
in functions (commands) for creating particular kinds of matrix. Frequently-used
examples include the following.
ones Create a matrix (or array) of all ones
zeros Create a matrix of all zeros
rand Create a matrix of uniformly distributed random numbers
randn Create a matrix of normally distributed random numbers
Matrix concatenation is the process of joining one or more matrices to make a new
matrix. The brackets [ ] operator discussed above serves not only as a matrix
constructor, but also as the concatenation operator. The expressions C = [A B] or
E = vertcat(A,C)
G = repmat(F,2,3)
A(3,2), A(7)
ans =
6
To convert between index styles, use sub2ind and ind2sub, where sub refers to
row-column indexing. E.g.
linearindex = sub2ind(size(A),3,2)
linearindex =
7
For non-sequential access, an integer-valued matrix can also be used for indexing.
A([1,4,9])
ans =
6 4 2
Logical true and false states are represented in MATLAB as 1 and 0, respectively
(see section 4). Logical values can be used for matrix indexing in MATLAB and
this is an efficient and general method for selecting arbitrary matrix elements. A
logical indexing matrix is normally the same size as the matrix being accessed and
the indexing operation here is based on the position of true values in the indexing
matrix. In the following example, we use logical indexing to blank out the smaller
values in A.
L = A<5
L =
0 1 1 0
0 1 1 0
1 0 0 1
1 0 1 1
A(L) = 0
A =
6 0 0 8
5 0 0 7
0 6 7 0
0 5 0 0
ans =
2 3
length(F)
ans =
3
numel(F)
ans =
6
Size and length are particularly useful and frequently used functions.
Certain functions test the data type of a matrix, returning a logical value to indi-
cate the result (see section 4). These include the generic isa function and specific
functions such as isfloat, isinteger, isnumeric, and islogical.
Other functions test the structure of a matrix, such as isvector, isscalar and
isempty. These function are useful for avoiding errors caused by special cases. For
example, say you have a program designed to perform an operation on paired data
stored in a 2-by-N matrix, where N may vary. In the general case, with N > 1, we
could use length to determine the number of data pairs, but this approach may fail
for N = 1 (where length is 2), and N = 0 (where length is 0). Calls to isvector
and isempty could check for these special cases.
F(1,5) = 3
F =
1 2 3 0 3
4 5 6 0 0
F(1:2,5:6) = 8
F =
1 2 3 0 8 8
4 5 6 0 8 8
Conversely, you can delete rows and columns from a matrix by assigning the empty
array [] to those rows or columns.
F(:,6) = []
F =
1 2 3 0 8
4 5 6 0 8
F = [1,2,3;4,5,6]
F =
1 2 3
4 5 6
fliplr(F)
ans =
3 2 1
6 5 4
transpose(F)
ans =
1 4
2 5
3 6
reshape(F,3,2)
ans =
1 5
4 3
2 6
circshift(F,[0,1])
ans =
3 1 2
6 4 5
A =
6 3 2 8
5 1 3 7
1 6 7 2
4 5 4 1
sort(A)
ans =
1 1 2 1
4 3 3 2
5 5 4 7
6 6 7 8
sort(A,2)
ans =
2 3 6 8
1 3 5 7
1 2 6 7
1 4 4 5
By default, sort sorts in ascending order, but an additional argument can be used
to specify descending-order sorting:
sort(A,2,’descend’)
ans =
8 6 3 2
7 5 3 1
7 6 2 1
5 4 4 1
sortrows keeps elements of each row in its original order, but sorts the rows accord-
ing to the order of the elements in a specified column (the first by default).
sortrows(A)
A =
1 6 7 2
4 5 4 1
5 1 3 7
6 3 2 8
Step 1
Task 5 Create a matrix F that is actually part of matrix E.
Matrix resizing and sorting More specifically F should consist of the rows 2 until 4
and columns 1 until 4 of matrix E.
Step 2
Identify the size of each dimension of the new matrix F
and display them on the command window.
Step 3
Assuming now that matrix F has m rows and n columns,
reshape matrix F in order to have n rows and m
columns.
Step 4
Create a matrix G that will be matrix F sorted along
column in a descending order.
Step 1
Task 3 After running the script created so far, look at the el-
Restore the original square ements of A, B and C in the Command Window (type
in the variable name and press Enter).
Step 2
The original magic square (A) can be extracted from C
using row-column sequential indexing. Try it, assigning
the output to (D). See section 3.4 for guidance.
Step 3
Add a line to verify that D is equal to A using isequal.
Step 4
The elements of A can also be extracted from C using
linear indexing, taking every 4th value starting from 1
and ending at a suitable number to extract 9 elements
in total. Try this and assign the output to E. Consider
how you could convert E into the original magic square
form and test this in your script.
Not all functions work for all data types. For example, sin is a built in MATLAB
trigonometric function which is not defined for integer types.
Strings are useful when working with and displaying text data, displaying warning
and error messages during program execution, and naming variables and files.
Strings are also commonly used to provide categorical inputs to MATLAB commands
(functions). See the Function and Command Syntax box in section 9.1 for further
details.
num2str is a function that converts numbers to character or string values. This can
be useful for labelling figures, and working with numbered files. Here is an example
of how num2str can be combined with matrix concatenation (recall section 3.3) to
reference a numbered file:
filename = [’DataFile’,num2str(400)]
filename =
DataFile400
str2num (or str2double) converts strings to numeric values, which can be useful
when data has been imported from an ASCII file for example.
Operators and control statements add power and flexibility to MATLAB pro-
grams. Operators are used to perform arithmetic, numerical and logical operations,
using program statements that are concise and easy for a person to read.
There are two major types of arithmetic operations. Array operations are carried
out element by element and the operand matrices must be of the same size, unless
one is scalar. Matrix operations are defined by the rules of linear algebra. The
full stop character (.) distinguishes the array operations from the matrix operations.
For addition and subtraction, the matrix and array operations are the same, and
here the full stop is not used. Tip: It is a common error to confuse matrix and array
operators. Always consider which you should be using in a given situation. Below
is a brief summary. For further details, look here.
+ and - Addition and subtraction. A+B adds A and B. A-B subtracts B from A.
.* Array multiplication. A.*B is the element-by-element product of the
arrays A and B.
.^ Array power. A.^B is the matrix with elements A(i,j) to the B(i,j)
power.
./ Array right division. A./B is the matrix with elements A(i,j)/B(i,j).
.\ Array left division. A.\B is the matrix with elements B(i,j)/A(i,j).
* Matrix multiplication. A*B is the linear algebraic product of A and B.
For nonscalar A and B, the number of columns of A must equal the
number of rows of B.
^ Matrix power. In the non-scalar power case, the calculation here in-
volves eigenvalues and eigenvectors.
/ Matrix right division. B/A = (A’\B’)’.
\ Matrix left division. X = A\B is the solution to the equation AX = B.
Relational operators share the same general form as arithmetic operators, and
are used to compare operands quantitatively, using operators like “less than”. Like
array arithmetic operators, relational operators always operate element-by-element.
If one operand is scalar, it is expanded to the size of the other operand. These
operators return a logical array reflecting the outcome of the relational test. Here
is a summary:
5.4 Conditionals
Conditional statements control program flow by selecting which blocks of code to
execute based on the value of test expressions. They allow a MATLAB program to
perform multiple tasks based on its inputs.
if statements perform selection based on the value of a logical expression. In its
basic form, an if statement has this form:
if logical-expression
statements
end
The statements within the if statement are executed only if the logical expression
is true. Otherwise those statements are skipped, and execution continues following
the end line. For example:
if isprime(a)
disp(’prime number detected’)
end
If the logical expression evaluates to a nonscalar value (e.g. a vector), then all the
elements of the argument must be true (nonzero) for the expression to be evaluated
as true. Note also that if statements can be nested by putting one inside another.
The following example performs the same function as the preceding one:
if isprime(a)
if a>100
disp(’Big prime number detected’)
end
end
For more complex conditional evaluations, the else and elseif statements can be
incorporated into an if statement. The general form here becomes:
if expression1
statements1
elseif expression2
statements2
.
.
.
else
statements3
end
where any number of elseif groups can be used, and the else group is optional.
The code above will execute statements1 if expression1 is true. If expression1
is false, and expression2 is true, then statements2 will be executed. In all other
cases, statements3 will be executed.
Switch statements
switch statements select between multiple code blocks based on the value of a
single variable or expression (the switch). The basic form is:
switch expression
case value1
statements1
case value2
statements2
.
.
.
otherwise
statements3
end
In a switch statement, any number of case groups can be used, and the
otherwise group is optional. In MATLAB (unlike C), if any case statement
is true, subsequent cases are not evaluated or executed.
5.5 Loops
Loop control statements enable a code block to be repeatedly executed. There are
two loop types in MATLAB: for and while.
for loops execute a code block a number of times determined on entry to the loop.
The syntax normally uses the colon operator introduced in section 3.
for index = start:increment:end
statements
end
for loops can be nested and this can be useful to access each element in a two-
dimensional matrix. However, nesting loops in MATLAB can result in slow code
execution, especially for nesting beyond two levels. Fortunately, there are ways to
avoid using heavily nested loops in many circumstances, and we will look at this in
section 10.
while loops repeat execution of a block of statements as long as a test expression is
true.
while expression
statements
end
To avoid infinitely-repeating while loops, one or more statements inside the loop
must change the value of the test expression (although see the break statement
below). This is in contrast to the for loop, where the statements inside the loop do
not generally affect the number of loop repeats. Compare:
n=10
for i=1:n
n=n-1
end
n=10
while n>0
n=n-1
end
Step 1
Task 2
The first six numbers of the Fibonacci sequence are: 0,
Sum of Fibonacci numbers
1, 1, 2, 3, 5. In order to calculate each number Fn of the
Part I
sequence, the previous two numbers, Fn-1 and Fn-2 are
required. The formula is: Fn = Fn-1 + Fn-2. Create a
matrix F that will contain the Fibonnaci sequence and
fill the first two elements with 0 and 1 respectively.
Step 2
Create a ’for’ loop that will calculate the first 20 num-
bers of the Fibonacci sequence. Every time a new num-
ber is calculated it must be displayed on the command
window.
Step 3
Create a variable sumFib that will contain the sum of
the calculated Fibonacci numbers. Initialize this vari-
able with 0. Every time a new number from the Fi-
bonacci sequence is calculated within the for loop, this
variable will be updated by adding the new number.
Step 4
When the ’for’ loop terminates, display a message re-
garding the sum of the first 20 Fibonacci numbers. Con-
sider using the function num2str to transform the value
of the sumFib variable into a string in order to be in-
corporated in the displayed message.
Task 3 Step 1
Sum of Fibonacci numbers Copy the Fibonacci Sequence.m script and rename it
Part II into Fibonacci Sequence2.m
Step 2
Replace the ’for’ loop with a ’while’ loop that will again
calculate the Fibonacci numbers, add them, and the
result must be saved again in the variable sumFib. A
criterion for the ’while’ loop is required. This criterion
should be that the summation of the Fibonacci numbers
calculated so far must not exceed 1000.
Step 3
When the ’while’ loop terminates, display a message
regarding the sum of the Fibonacci numbers calculated
so far, as well as the number of the Fibonacci numbers
required to reach the termination criterion of the ’while’
loop. In order to achieve this, consider defining a new
variable that will act as a counter of the ’while’ loop
iterations, and it must be updated at each iteration.
6 Programming Fundamentals
Rather than entering commands into MATLAB one at a time at the command line,
you can also write a series of commands to a program file that you then execute as
you would any MATLAB function.
We already explored some programming essentials in section 2.6 and exercises 2-4.
In particular, we introduced both the MATLAB Editor, and the simplest kind of
MATLAB program file (M-file): the script. In this section we will go into a little
more detail.
In actual fact, there are two kinds of M-file:
• Scripts, which do not accept input arguments or return output arguments.
They operate on data in the workspace.
• Functions, which can accept input arguments and return output arguments.
They operate in private workspaces: internal variables are local to the
function.
6.1 Scripts
Scripts are simply a list of commands stored in an M-file. When you invoke a script,
MATLAB executes the commands found in the file. The result is exactly the same
as if the commands were entered one-by-one in the command window.
Scripts share the base workspace with your interactive MATLAB session and with
other scripts. They operate on existing data in the workspace, or they can create
new data on which to operate. Any variables that scripts create remain in the
workspace after the script finishes so you can use them for further computations.
6.2 Functions
Functions are program files that can accept input arguments and return output
arguments. The names of the file and of the function should be the same.
Each function operates on variables within its own workspace, which is separate from
the workspace you access at the MATLAB command prompt. The input arguments
are the initial contents of the private function workspace, and the output arguments
are what is returned to the workspace from which the function was called. Since
functions can call functions, there can be a hierarchy of separate, private workspaces.
The first line of a function starts with the keyword function. It gives the function
name and order of arguments.
6.3.1 Comments
The first lines of the file are preceded by percent symbols, which in MATLAB
denote comments. A comment is a message to someone reading or editing the M-
file and the text is not interpreted as code by MATLAB. The first paragraph of
comments at the top of an M-file is used to explain the intended usage of the script
or function. These comments are also harvested for the MATLAB help system:
help tutorial script1.
Additional comments should be used in the body of the file to explain particular
sections or lines of code. Finally, comments are also useful for temporarily disabling
a piece of code during development. This is referred to as ‘commenting out’ code.
Below the first help paragraph is a section of housekeeping code, used to keep the
MATLAB workspace and display area tidy. In the tutorial example, we use clear
to clean up the workspace, close to close figures, and home to tidy up the command
window. A commented out line gives the option of using clc instead of home.
I put housekeeping code at the start of my scripts, but it is also reasonable to put
it at the end. Limited housekeeping can also be useful in the middle of a script, but
you certainly would not want to use clear all here!
The script body is the main subsection of executable code. Here it draws a circle,
using built-in MATLAB trigonometric functions.
• First, the centre co-ordinates and radius of the circle are declared and re-
ported using disp.
• Next, a vector (theta) of N=1000 parameter values is created, evenly spaced
between 0 and 2pi. The standard parametric equations for a circle are
applied to calculate x and y co-ordinate pairs for the perimeter of the circle.
• Finally, the circle is plotted in a figure window, and modified to display in
the correct aspect ratio, using axis. pause is one way of interrupting pro-
gram flow, and potentially requiring human interaction with the program.
Running the script There are two main ways to run a script in MATLAB.
1. From the Command Window, you can enter the script name. Note, this
only works if the script is either in the current folder or the path.
2. From the Editor, you can press F5, or click the Run button (which features
a green ’play’ triangle).
In MATLAB, function is a special function used to declare all other functions. The
function declaration must be the first executable line of any MATLAB function, and
follows the form:
function [out1, out2, ...] = myfun(in1, in2, ...)
tutorial fun1.m has inputs called C, R and FIG, and an output called CIRCLE.
The help comment block is the first paragraph of comments in the function, and
normally follows the function declaration. In tutorial fun1, the help comment block
is written in the general form of standard MATLAB functions. Compare:
help tutorial fun1, help fliplr.
It is good practice (but not essential) to write help comment blocks in this form.
The body of tutorial fun1 is similar to that of tutorial script1. Both script and
function perform the same basic task but there are differences:
• The calls to disp and pause have been removed in the function
• In the script, the centre co-ordinates, radius and figure number are declared
as constants, while in the function they are read in as input arguments
• In the function, a line has been added to form the output matrix
Step 4
Steps1-3 must also be followed when the second player.
Make sure you copy this code at the right place and
make the necessary changes in the variables and mes-
sages to be displayed so that they correspond to the
second player.
Step 5
The board has a limited number of squares, 9 specif-
ically. So far, the program allows each player to play
only once. In order for the game to continue, one player
must play after the other and the criteria for the game
termination should be either to have a winner or to
fill completely the board. Since now only one round
of the game has been implemented in the code, a loop
needs to be introduced that will allow repetitive rounds
as long as the criteria for the termination of the game
have not been satisfied. Hint: Consider using the ’avail-
able squares’ variable, which is updated every time a
player finishes their round, as a criterion to the loop.
6.6 Debugging
• Syntax errors: occurring when the syntax used to call a function or to use
an operator is incorrect. In these cases, MATLAB provides you with an
error message indicating the location and type of error.
Debugging is useful mostly in the cases where it is not clear where the error is or
it originated from. There are several debugging tools available in MATLAB, and in
this section the most commonly used are presented:
• By left-clicking on the dash line next to the number of the line where we
want the breakpoint to be placed.
• By placing the cursor anywhere on the desired line and then clicking Editor
→ Breakpoints → Set/Clear (or pressing F12 on the keyboard).
When the user runs a program, the execution will stop at the line where the first
breakpoint is placed. Then the user has the following options:
• Click Continue: the execution will continue until the next breakpoint is
met. If there are no breakpoints later in the code, the program will execute
until it terminates.
• Click Step: when this option is chosen, the current line of the program
will be executed and the execution will stop at the next line. This button
provides the user with a way of investigating step-by-step the functionality
and results of the code.
• Click Step In: This option provides you access to the content of a function
called at the line where the execution of the program currently is. Then by
using Step, the user can go through each line of this function.
• Click Step Out: This option allows the user to step out of a function that
has previously stepped in without executing some or all of the lines in this
function.
• Click Quit Debugging: This option terminates the execution of the program
and allows the user to have access to the command prompt, and edit the
m-files.
Using a try / catch block A special case of debugging is the try/catch block, and
its structure is shown below.
try
some code
catch
error handling code
end
This block is used to capture errors in specific lines in the code whose execution is
expected to fail under specific circumstances, and avoid failure of the entire program.
The part of the code that is right after the try section corresponds to the code being
executed and checked for errors, and the part of the code that is after the catch
section corresponds to the code being executed when an error has been captured.
• dbquit: to terminate the execution of the program and exit the debug
mode.
6.7 Toolboxes
MATLAB Toolboxes are specialized sets of functions serving a wide variety of pur-
poses, including data analysis, data acquisition, signal and image processing, parallel
computing, statistical data analysis, controller design and implementation.
Depending on the MATLAB license there are different toolboxes available. In order
to access the installed toolboxes in a system, the ver command can be entered in
the Command Prompt, which produces a list of installed toolboxes. Then by using
the help command along with the toolbox directory name, a list of the functions
available in the specific toolboxes is produced. The available MATLAB toolboxes
are listed here: http://uk.mathworks.com/products/
y = [1.5*cos(x)+4*exp(-.01*x).*cos(x)+exp(.07*x).*sin(3*x)];
plot(x,y)
xlabel(’X Axis’)
ylabel(’Y Axis’)
Various MATLAB commands are useful for setting up figures. We consider a few of
the most useful here.
7.2.1 figure
7.2.2 subplot
To place multiple plots on a single figure, in a regular tiled pattern, you can use
subplot. For example:
subplot(2,3,4)
defines a 2-by-3 grid on a figure and opens or selects the 4th subplot counting
along rows, from the top left. Note that subplot creates an axes in the position
specified. A graphics command at this point will output to this axes object. Try
plot(rand(1,10)). Another call to subplot will create/select a different axes:
subplot(2,3,2)
It is usually a good idea to use the same tiling grid in multiple calls to subplot on
a single figure because, when subplots overlap, the existing axes is deleted.
subplot(2,4,5)
subplot(2,2,2)
subplot(4,4,1)
subplot(4,4,2)
subplot(4,4,5)
subplot(4,4,6)
With Data Linking, such a figure can be used for continuous monitoring of multiple
data streams.
For complete flexibility, you can use the position argument: subplot(’Position’,[left,
bottom, width, height]), which creates an axes at the position specified by a 4-
element numerical vector with normalised coordinates in (0,1). For example:
close all
axes can be used to create an axes, and/or specify its properties. axes on its own
creates an axes object in the current figure using default properties. Alternatively,
axes(’PropertyName’,PropertyValue,...) creates an axes object having specific
property values in name-value pairs. We will cover these properties in detail in
Graphics 2, but here is a simple example:
close all
axes(’Box’,’on’,’Color’,’y’)
axis is used to manipulate commonly used axes properties, such as the axis limits:
axis([xmin, xmax, ymin, ymax]). Be careful not to confuse axis and axes.
Step 1
Task 1
To get started, create the graph from section 7.1, com-
Open the Plot Tools
plete with text labels, via copy and paste.
Step 2
Click the Show Plot Tools icon in the figure window.
Step 1
Select the axes by either clicking in the central white
Task 3
area or clicking the axes title in the Plot Browser tool.
Edit the Axes Properties
Step 2
Toggle the axes visibility off and on using the tick box
next to the axes title in the Plot Browser.
Step 3
In the Property Editor, change both the fill and line
colours to contrast with each other and the background.
Step 4
Toggle the x and x grids on and off in the Property
Editor, and toggle the box off and on.
Step 5
Examine the limits of each axis in the Property Editor
and change the font to SansSerif.
Step 1
Task 4
Select the line plot by clicking on the line in either the
Edit the Line Plot Properties
main figure window or the Plot Browser.
Step 2
In the Property Editor, try each of the Plot Types,
before returning to the original line plot.
Step 3
Try each line style, and increase line thickness to 2.0 in
the Property Editor.
Step 1
Task 5 With the Figure Palette Tool, you can add subplots to
The Figure Palette your figure, change variable names and plot types, and
add annotation to the figure.
Step 2
Add, and then delete, some Annotation features.
Step 3
The Plot Catalogue Tool offers GUI access to many plot
types. To open it, right click y in the Variables box and
choose Plot Catalogue.
Step 4
In the Plot Catalogue Tool, change Plotted Variables to
x,y, choose comet and click Plot in New Figure. Then
close the new figure and the Plot Catalogue window.
Step 1
If you have just finished the previous exercise, select
Task 1
Hide Plot Tools on the Figure Toolbar. If you need to
Zoom
generate the graph again, copy and paste the earlier
code into the Command Window.
Step 2
Select the Zoom In tool.
Step 3
Move the mouse pointer inside the axes noting how the
pointer changes to the zoom in symbol. Left click once
near the line plot and note how the display changes.
Repeat this process several times. To return to the
default zoom level, double click anywhere in the axes.
Step 4
For a more controlled zoom, drag a selection box over
an area (left click-and-hold, drag, release). The axes
is redrawn, changing the limits to display the specified
area. Double click to restore the original zoom.
Step 5
For a constrained zoom, right click in the axes with
the Zoom In tool selected, and choose Horizontal Zoom
from Zoom options. Drag a selection range to see how
this works before returning to the default zoom level.
Step 1
Task 2
Pan Select the Pan tool from the Figure Toolbar.
Step 2
Click, hold, and drag to pan.
Step 3
Pan works a lot like zoom in that double clicks return to
the default view, and there are both unconstrained (de-
fault) and axis-constrained versions available through a
right-click menu.
Step 4
Try both Horizontal and Vertical panning, before re-
turning to the default view.
Task 3 Step 1
Rotate
Select the Rotate tool from the Figure Toolbar.
Step 2
Grab the axes with a left click-and-hold, and move the
graph around in three dimensions by moving the mouse.
This option is not so useful with a two-dimensional
plot, but can be useful for visualising three-dimensional
datasets. Restore the original view with a double click.
Step 1
Task 4
Select the Cursor tool from the Figure Toolbar.
Cursors
Step 2
Left Click somewhere on the line plot to place a cursor
(or data tip) on the graph. Left click and drag to move
the cursor around over the graph.
Step 3
To place additional data tips, right click and choose
Create New Datatip.
Step 4
Right click and select Delete All Datatips.
Step 1
Task 5
Data brushing is used to interactively select data for
Data Brushing
further analysis or modification. Select the Data Brush-
ing tool and drag a selection box inside the axes to
choose a dataset.
Step 2
Right click on the brushed data, choose Create Variable
and save the brushed data as a named variable.
Step 3
Other options in the Brush menu include Remove (to
remove the brushed data from the graph), Remove Un-
brushed, and Replace With (to replace all brushed data
point y values with a constant value).
Step 1
Task 6
Linked plots are graphs in figure windows that visibly
Data Linking
respond to changes in the current Workspace variables
they display and vice versa. Select the Data Linking
tool and note the Linked variables line that appears
below the Figure Toolbar.
Step 2
In the Command Window, alter the value of y using
y=y.*x (or similar) and observe the resulting changes
in the linked figure.
Step 3
Switch off linking by deselecting the linking tool and
note how further changes to the data values are ignored
in the unlinked plot.
Most plot types are accessible through the GUI, via the Plot Catalogue (see Exercise
5), but they can also be produced from the command line. In the remainder of this
section, we focus on the 2D line and bar graphs, via the exemplar functions plot
and bar.
plot is the standard MATLAB line plotting function. If y is a vector, then plot(y)
produces a piecewise linear graph of y versus the index of its elements, 1:length(y).
If you specify two vector arguments, plot(x,y) plots y versus x. Thus, plot(y) is
shorthand for plot(1:length(y),y). Expanding on our earlier example:
x = -10:.1:40;
y = [1.5*cos(x)+4*exp(-.01*x).*cos(x)+exp(.07*x).*sin(3*x)];
figure(1); clf;
subplot(3,1,1)
plot(y)
subplot(3,1,2)
plot(1:length(y),y)
subplot(3,1,3)
plot(x,y)
A simple way to alter the properties of the lineseries plotted is to add a LineSpec
string after the x,y pair, which consists of a triplet specifying Line Style, Marker
Symbol and Color (in any order). For example:
subplot(3,1,3)
plot(x,y,’r:x’)
Almost all high level line plotting functions accept LineSpec string arguments, so it is
well worth learning them. More detailed property manipulation is available through
PropertyName, PropertyValue pairs, as we saw above for axes. For example:
plot(x,y,’r-s’,’MarkerEdgeColor’,’b’,’MarkerFaceColor’,’y’)
plot(x,y-20,’b-s’,’MarkerEdgeColor’,’g’,’MarkerFaceColor’,’r’)
plot(x,y+20,’c-s’)
If one or both of an x, y pair is a matrix, multiple lines (one for each column) are
plotted using cycling, contrasting colours.
subplot(3,1,1)
plot(magic(9))
Finally, any call to plot can return a column vector of handles to lineseries objects,
one handle per line.
Bar graphs display vector or matrix data as vertical (bar) or horizontal (barh)
bars. bar(Y) draws one bar for each element in Y. If Y is a matrix, bar groups
the bars produced by the elements in each row. The x-axis scale ranges from 1
subplot(3,1,1)
bar(magic(5))
subplot(3,1,2)
barh(magic(5))
subplot(3,1,3)
bar(magic(5),’stacked’)
h1 = figure
h2 = axes(’Box’,’on’,’Color’,’y’)
In addition, handles for the current figure and current axes are returned by gcf, and
gca. Using an object handle, you can alter the properties of an existing graphics
object. You can also specify property values when you create a graphics object, as
we saw above for axes and plot.
Graphics object properties allow us to flexibly alter figure appearance. To see the
extensive range of options available, here are links to lists of Figure Properties,
Axes Properties, and Lineseries (or Chart Line) Properties, with the latter
being the type of plot object created by plot. For an overview of object properties,
use this link.
Objects are organised into a hierarchy in MATLAB, with figures being the children of
the root object, axes being children of figures and plot objects being children of axes.
The child-parent relationship within the figure→axes→plot object hierarchy can
be used to reference related components within a complex graphical display setup.
Step 1
Use handles = get(gca,’Children’) to get handles for the
Task 4
three graphs; handles will be a 3 element vector
Adjust graph properties
Step 2
Use get with (elements of) the handles vectors to ex-
amine the graph properties. Use linear matrix indexing
here. Can you work out which handle is for which line?
Step 3
Use set with handles to change the marker size in each
graph (MarkerSize).
Step 4
Use legend to give the figure a legend with text labels
for each graph.
Step 5
Use set with handles to make one graph invisible (Vis-
ible off).
imfinfo peppers.png
peppers = imread(’peppers.png’,’png’);
image(peppers)
To remove axis ticks and set the correct aspect ratio for an image you can run
axis off
axis image
set(gca,’Position’,[0 0 1 1])
Note, when you set the axes Position to [0 0 1 1] so that the displayed image fills
the entire figure, the aspect ratio is not preserved in printing because MATLAB uses
the PaperPosition property to determine printed size and shape. To preserve the
aspect ratio when printing, set the PaperPositionMode to auto as follows:
set(gcf,’PaperPositionMode’,’auto’)
Images can be cropped in MATLAB using sequential matrix indexing. For example:
peppercrop = peppers(1:(m/2),1:(n/2),:);
figure; image(peppercrop)
• Print to File
• Export to File
• Export to Clipboard
These can be accessed via either the Command Line or the Graphical User Interfaces.
We consider the former here, and the latter in exercise 12 below. The general printing
and export function is print. On its own, print send the contents of the current
figure to the printer using the printing options specified by printopt (this usually
sends printout to the default printer). The table below summarises further options
available through the addition of input arguments to print.
handle Print the specified object
filename Print to a named PostScript file
-ddriver Print using a specified driver (default is in printopt)
-dformat Export to the clipboard (Windows only). Format must be
either -dmeta or -dbitmap.
-dformat filename Export the figure to file using a specified graphics format.
-options Specify additional printing options.
To demonstrate some options, we start with an annotated peppers image:
annotation(’textarrow’,[.2,.3],[.8,.6],’String’,’Chili’,’Color’,’w’);
set(gcf,’InvertHardcopy’,’off’)
and copy to the clipboard (so you can paste it into a word document for example):
print(h,’-dmeta’)
print(h,’-dpsc’,’PepperFig.ps’)
print(h,’-dpdf’,’PepperFig.pdf’)
9 File Handling
MATLAB is able to import and export data from many different file types, and
different import and export methods are used for each type. In this section, we look
at four of the most common file types. Image data files are covered in section 8.2.
9.1 MAT-Files
MAT-files are the default data storage file type in MATLAB. They are binary files
that can store the variables in your current workspace for later use. MAT-files use
the .mat extension.
To import and export from MAT-files, we can use the load and save functions.
save, by itself, creates a binary MAT-file named matlab.mat in the current folder,
and saves all current variables in the workspace into that file. load, by itself, loads all
the variables stored in matlab.mat into the current workspace, overwriting existing
values. For example:
x = 2
y = 5
save
x = 5000
load
This is not generally the most useful way to use these functions, since each save will
overwrite any previously saved data. Instead we can include a filename argument.
Additional arguments can be used to load or save only particular variables:
save temp x
x = 5000
y = 25
load temp
To inspect the values in a saved file, we can use the command whos -file filename.
This function returns the name, dimensions, size, and class of all variables in the
specified MAT-file. Both whos -file and load will search the MATLAB path as
well as the current folder.
which durer.mat
load durer.mat
It is also possible to use the GUI to inspect and load MAT-file data. To see the
variables in a MAT-file before loading the file into your workspace, click the file
name in the Current Folder browser. Information about the variables appears in the
Details Panel (bottom left of the GUI). Double clicking loads all the data from the
selected file into the workspace. To select and load MAT-file variables interactively,
use any of the following options:
• Drag variables from the Details Panel of the Current Folder browser to the
Workspace browser.
To save data via the GUI, use either of the following options:
• Drag variables from the Workspace browser to the Current Folder browser.
Best Practice
While GUI tools may be easier to use when you are getting started, command
line methods are much more powerful in MATLAB. In particular, the GUI is only
useful for interactive sessions and not for automation.
The xlsread function is flexible, and a useful feature is the ability to separately
read in numeric and text data. For example, open up the hospital.xls example excel
spreadsheet (from the MATLAB stats toolbox demo), in Excel. Next, import the
data into MATLAB using:
[num,txt] = xlsread(’hospital.xls’);
Looking at the Workspace Browser, you will see that the text data have been im-
ported into a MATLAB as a cell array. A cell array is a collection of containers
called cells and each cell can store data of different sizes and types. Here, the cell
array is used to store strings of different lengths.
For spreadsheets with multiple worksheets, xlsread only imports the first worksheet
by default. To import a different worksheet, you can get the names of the sheets
using xlsfinfo, and then read in a named sheet:
[type, sheets] = xlsfinfo(’USTreasury.xls’)
Note the braces around the number 2 here. This is how you reference the contents
of a cell in a cell array.
To interactively select data from excel worksheets, use -1 in place of a sheet name:
[num,txt] = xlsread(’USTreasury.xls’,-1)
The counterpart to xlsread is xlswrite. With xlswrite, you can export data
from the Workspace to any worksheet in an Excel file, and to any location within
that worksheet. By default, xlswrite writes to the first worksheet in a file, starting
at cell A1. If the target file already exists, xlswrite writes data in the existing
format. If not, a new file is created using the format corresponding to the file
extension specified (the default is .xls). If Excel is not installed, xlswrite exports
to a .csv file.
There are many methods available in MATLAB to import to and export from
ASCII data files.
The load and save functions can work with text rather than binary files, if an
additional argument is added. For example:
x = magic(3);
save(’temp.txt’,’-ascii’)
Alternatively, you can launch the generic import wizard GUI by clicking the
Import Data button or running uiimport. The importdata function is largely
equivalent but without a graphical interface.
For ASCII files, uiimport and importdata should automatically detect:
• Row and column headers.
• Numeric
Non-numeric data headers can be handled by calling uiimport or importdata, with
function syntax and a single argument, as we saw for excel files:
mydata = importdata(’headers.txt’)
fid = fopen(’temp.bin’,’w’);
fwrite(fid, x);
fclose(fid);
y = fread(fid)
fclose(fid);
By default, fwrite writes the values from a matrix in column order as 8-bit unsigned
integers (uint8). Also by default, fread reads a file 1 byte at a time, interpreting
each byte as a uint8. fread creates a column vector output, with one element for
each byte in the file. The values in the output vector are of type double (the default
MATLAB numerical data type).
To read only a specified number of values, or import into two dimensional matrix,
a size argument to fread can be added as follows:
fid = fopen(’temp.bin’);
y = fread(fid, 4)
frewind(fid);
y = fread(fid, [2,2])
frewind(fid);
y = fread(fid, [2,inf])
fclose(fid);
To write and read with a different precision, add a precision string argument:
xpi = pi*x
fid = fopen(’xpi.bin’,’w+’);
frewind(fid);
fclose(fid);
Step 5
Clear the magic square variables from the workspace
and read them back in from the Excel spreadsheet using
xlsread in interactive mode (set sheet to -1) to read
the magic squares back into MATLAB. Select the data
before clicking OK in the pop-up box.
Step 1
Using fopen, open a binary file called magic.bin for
Task 3 reading and writing, discarding existing contents. Use
Binary Files help to choose an appropriate permission string for
fopen.
Step 2
Using fwrite, write the small magic square to the start
of the binary file.
Step 3
Clear the small magic square variable and use frewind,
and fread to rewind the file and then read the small
magic square back in from the open binary file. You
will need to give a size argument to fread. See the
examples in section 9.4 for guidance.
Step 4
Close the binary file using fclose and reopen it in ap-
pend, read-write mode (a+). Write the large magic
square to the end of the file.
Step 5
Rewind the file, and read in both magic squares from
the binary file.
Step 6
Finally, close the binary file.
Key Functions xlsread, load, plot, XTickLabel, for, sort, sum, bar,
disp
Step 1
Task 1
Open the Excel file named ’UK demographics.xls’ in
Open Excel and MAT Files
the H:\Matlab\tutorial4 directory outside Matlab and
study the different sheets and fields.
Step 2
Open the Excel file named ’UK demographics.xls’
through MATLAB and assign the different sheets in
different variables, as it has been demonstrated in this
chapter.
Step 3
Open the MAT file named ’EuropeanUnionDemograph-
ics.mat’ in the H:\Matlab\tutorial4 directory through
MATLAB. This file contains three columns: the first
one has the names of the countries in the EU, the sec-
ond has the population of each country, and the third
has the area (in km2 ) of each country.
Task 2 Step 1
Plot of the data Plot the UK population over time. The x axis of the
plot should have the corresponding years.
Step 2
Plot the UK population in 2011 with respect to the age
group. Then, change the x axis labels to correspond to
the different age groups. In order to do this, consider
using the plot property ’XTickLabel’.
Step 1
Task 3
Create a new script and name it ’UKpopulationIn-
UK population Increase rate
creaseRate.m’.
Step 2
Using the UK demographics over time data, calculate
the rate of population change over year. For example
for year 2010, the rate is (population in 2010 - pop-
ulation in 2009)/(population in 2009). Save this data
along with the corresponding year in a matrix called
’PopulationChangeRate’.
Step 3
Sort the ’PopulationChangeRate’ matrix and display
the year with the highest population change rate. Con-
sider using either a loop to examine all the data and
find the highest value, or the MATLAB function ’sort’.
Task 4 Step 1
Age structure of UK Create a new script and name it ’UKpopulation-
population AgeStructure.m’.
Step 2
The UK population in 2011 for five year bands is given.
Categorize the UK population according to larger age
groups, i.e. 0-14, 15-64, 65+, and calculate each groups
population. Then, calculate the total population for
that year and the percentage for each age group.
Step 3
Plot using bar plots the population of each group. In
the axis display the age range for each group.
Step 1
Task 5
Create a new script and name it ’EUcountriesPopula-
Population density of EU
tionDensity.m’.
countries
Step 2
Using the EU demographical data, calculate the popu-
lation density of each country.
Step 3
Sort the EU countries according to population density
in descending order.
Step 4
Display a message with the countries that have the
highest and lowest population density.
10 Performance
MATLAB is an interpreted computing system. This means that the code is not
generally compiled into a standalone program, like most applications you will find
on a desktop PC. Instead, the code is interpreted on the fly at run-time. The advan-
tages of an interpreted system include rapid development time and the MATLAB
GUI facilities. The disadvantage is that interpreted code tends to run slower than
compiled code, particularly when the code is not optimised. In this section, we look
at ways to monitor and improve the performance of a MATLAB program.
A quick way to check the speed of a particular section of code is to use the stopwatch
timer functions, tic and toc. Calling tic initialises the stopwatch timer, and a
subsequent call to toc returns the time elapsed since the last call to tic. Wrapping
any block of code in a tic toc pair should reveal how long that code takes to run.
For small programs, it may be more informative to calculate average run time.
tic
for i=1:1000
r=rand(500)*i;
end
t1=toc/1000
The profiler utility is a good way to work out where bottlenecks are in a program,
and can be particularly useful on large programs with many components. The
profiler generates a report that shows you a breakdown of which components of a
program take up most time during execution. For each MATLAB function in a
running program, profile records information about execution time, number of calls,
parent functions, child functions, code line hit count, and code line execution time.
The profiler is controlled using the profile function. Refer to the help files for an
explanation of the syntax and operation. To focus on function performance, GUI
output from the program should be minimised. Try this example to see why:
profile on
for i = 1:1000
figure(1); close all
r = rand(100);
end
profile viewer
Quick Tips
1. load and save are faster than low-level file I/O functions (see section 9).
2. Use logical indexing to quickly access non-contiguous matrix elements.
3. Don’t change a variable’s data type. When converting, create a new variable.
x = 10
x = num2str(x)
vs.
xs = num2str(x)
IT Learning Programme 72 2015
MATLAB: An Introduction
10.2.1 Preallocation
x = [];
for i = 1:10000
x = [x,rand(10,1)];
end
toc
clear; tic
x = [];
for i = 1:10000
x(:,i) = rand(10,1);
end
toc
clear; tic
x = zeros(10,10000);
for i = 1:1000
x(:,i) = rand(10,1);
end
toc
10.2.2 Vectorization
i = 0;
for t = 0:.01:10
i = i + 1;
for j = 1:100
y1(j,i) = sin(t)*j;
end
end
toc
tic
t = 0:.01:10;
j2 = repmat((1:100)’,1,length(t));
y2 = repmat(sin(t),100,1).*j2;
toc
numericalerror = max(max(y1-y2))
Step 5
Finally, the message decoding can be achieved using
either logical or linear indexing into the green and red
matrices (logical indexing requires less code). Add the
message to the subplot title by copying in code.
Task 3 Step 1
Vectorized Plot Marking pixels with squares can be approximately vec-
torized using a single plot statement, with row-column
indices from find, and square markers. You can see
the approximation using zoom.
Step 1
The supplied image cleanup code uses two for loops to
Task 4
perform median filtering in each channel over a neigh-
Vectorized Image Cleanup
bourhood around the message pixels.
Step 2
To perform the cleanup using no loops, you should cre-
ate an n x 9 matrix for each colour channel storing the
9 pixel values in the neighbourhood of each message
pixel. A single n x 9 x 3 array can also be used. To do
this, you should use indexing into the red, green, blue
matrices relative to the message pixel index locations
(given by find in Task 2). For example, the pixel just
to the left of reference pixel at location x is at x - m1
and the pixel above the reference is at x - 1.
Step 3
Start by creating a vector of 9 shift values (e.g. -m1 and
-1 for the examples above), then use repmat to extend
this to n x 9 and add the shift matrix to the message
coding pixel locations (repmat again) to calculate the
neighbourhood locations. The neighbourhood locations
can then be used as indices into the red, green, blue
matrices to extract the neighbourhood pixel values.
Step 4
Finally, use median in the second dimension to per-
form the cleanup filtering. Copy in the image display
code to inspect the results (using zoom to confirm pixel
cleanup).
11 What Next?
We hope you have found this book useful. If you attended a taught session you will
get an email with a link to a web page to give us anonymous feedback. We always
value your feedback and use it to improve our sessions.
You may like to consider the following options to follow on from these sessions.
11.1 Computer
We encourage everyone to work at their own pace. This may mean that you don’t
manage to finish all of the exercises presented in this booklet. If you would like to
complete the exercises while someone is on hand to help you, come along to one of
the Computer8 sessions that run during term time. More details are available at:
www.it.ox.ac.uk/courses/
11.4 Books
There are many MATLAB textbooks available, from general introductory texts to
application-specific guides. For a general introduction, try Getting Started with
MATLAB: A Quick Introduction for Scientists and Engineers (Rudra Pratap, 2010).
For a quick reference, try MATLAB Primer, 8th Edition (Timothy A Davis, 2010).
MATRIX CREATION
Constructor operator [ ]
Built-in functions: ones/zeros/rand/randn
MATRIX CONCATENATION
MATRIX SORTING Concatenation operator [ ]
Numeric Sequences Generation: colon operator
sort/ sortrows (first:last) Built-in functions:
cat/horzcat/vertcat/repmat
NUMERIC
Double/Single precision floating point numbers
Signed/Unsigned
Functions for convertion between datatypes:
int8/int16/uint8/uint16/single/double
MAIN
MATRIX
DATA TYPES
Logical Characters & Strings
String: a vector of characters surrounded by
Logical true or false represented as 1 and 0.
single quotes
Used for matrix indexing, conditional
Convertion between characters and numbers:
statements
num2str/str2num/str2double
Chapter 5: Operators
Operators •
•
>= : Greater than or equal to
== : Equal to
• ~= : Not equal to
• & : Logical AND (A&B returns true for every location that it is true in both arrays)
• | : Logical OR (similar as above)
Logical • ~ : Logical NOT (Compliments each element of the input array)
Operators • && : Short-circuit AND (Expressions on the left and right side. Outcome of the
operator depends on the outcome of each expression)
• || : Short-circuit OR (similar as above)
Chapter 5: Control Statements
Running Running
• From the Command Window by • From the Command Window by providing
entering the script name and pressing the input arguments and calling then the
ENTER function as: [out1,...]=myfun(in1,in2,..)
• From the Editor by pressing RUN or F5 • From a script or another function in which
the input arguments are declared and then
the function is called as before
Chapter 9: File Handling
types and
handling
Typographical Syntax
Incorrect syntax of calling a
Mispelling of a variable/command Algorithmic function or using an operator
Error message: Probably Error in the process followed by Error message: Yes
our code
Error message: Probably not