MATLAB
MATLAB
All rights reserved. No reproduction, copy or transmission of this publication may be made without written permission
from the authors. No portion of this publication may be reproduced, copied or transmitted save with written permission in
accordance with the provisions of the Copyright, Designs and Patents Act 1988 or any licence permitting limited copying
issued by the Copyright Licensing Agency, Saffron House, 6-10 Kirby Street, London EC1N 8TS.
Any person who does any unauthorised act in relation to this publication may be liable to criminal prosecution and civil
claims for damages.
The authors have asserted their rights to be identified as the authors of this work in accordance with the Copyright, Designs
and Patents Act 1988.
Copyright
c 2020 by Ludmila I. Kuncheva and Cameron C. Gray
ISBN 978-0-244-25328-8
Second Edition
Preface to the second edition
This is still a book containing exercise problems in MATLAB. The collection of problems covers basic
topics and is meant to stimulate student’s creativity in designing and implementing algorithms.
The respective elements of the language are briefly covered before the exercise section of each
chapter.
In this edition:
• We have revised the problem selection in view of some changes in the new MATLAB releases.
• We realised that the cost of the book does not make it suitable as an exercise notebook, so we
removed the spaces left for notes.
The reader should be aware that there are many ways to solve a problem, and the solutions that we
offer in this book are not necessarily the shortest or the most time-efficient ones. Some solutions are
chosen for their readability. Like most programming languages, MATLAB is developing from version
to version, and some of the commands explained and used here may alter in syntax or functionality in
the future.
The book could be useful for MATLAB course instructors as a set of ideas and examples to draw upon
when creating their own collections of problems.
Some of the problems assume knowledge of elementary algebra and geometry, or specific algorithms
such as bubble sorting, Monte Carlo and evolutionary algorithms. However, we kept the exposition
simple and self-contained, so that the book can be useful for a reader with minimal technical or
mathematical background.
The problems are of different difficulties. Some can be used in class tests or exams, while others
require more time and effort, and are more suitable for coursework. Solutions are provided only for
the examples in each chapter. Because the book is intended to be a personal hard-copy, we have left
spaces for handwritten answers and notes as shown below.
We enjoyed writing this book and hope that you will enjoy the intellectual workout.
4 Functions 36
4.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
4.2 Naming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.3 Multiple Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.4 Inline (Anonymous) Functions and Function Handles . . . . . . . . . . . . . . . . . . . . . . 37
4.5 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
4.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
5 Plotting 41
5.1 Plotting Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
5.1.1 Plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
5.1.2 Fill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
5.2 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
5.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
7 Strings 69
7.1 Encoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
7.2 Useful String Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
7.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
7.3.1 Imaginary Planet Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
7.3.2 String Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
7.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
8 Images 78
8.1 Types of Image Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
8.1.1 Binary Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
8.1.2 RGB Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
8.1.3 Grey Intensity Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
8.1.4 Indexed Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
8.2 Useful Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
8.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
8.3.1 Image Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
8.3.2 Tone ASCII Art . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
8.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
9 Animation 95
9.1 Animation Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
9.2 Mouse Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
9.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
9.3.1 Shivering Ball . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
9.3.2 Three Moving Circles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
9.3.3 A Fancy Stopwatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
9.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
11 Sounds 125
11.1 Sounds as Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
11.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
12 Solutions 132
Index 172
Chapter 1
Getting Started
1.1 MATLAB
MATLAB
R is a software package designed for mathematical and scientific computing. It is also
a development environment and a programming language. Its primary specialisation is efficiently
handling matrix and vector mathematics.
(2) Workspace
(memory)
(4) Command
history
Although MATLAB can execute commands typed straight in the Command Window, it is best to store
the code in a bespoke ‘m file’ or MATLAB script. A navigation button (top right in Figure 1.1) allows
1
2 CHAPTER 1. GETTING STARTED
the user to choose a folder where the work will be stored. Click on the ‘New file’ icon at the top left
corner. The editor window appears as shown in Figure 1.2.1
Run the whole file from here Run a cell from here
2. Highlight and copy the commands from the editor window and paste them in the Command
Window.
3. Highlight the commands in the editor window and press function key F9 . For Apple/OS X
machines, you should use + F7 (by default you will also need to hold the fn key to avoid
the ‘special’ meaning of F7).
4. Run the file with the commands in the editor window from the run icon, as indicated in Figure 1.2.
At the first run, MATLAB will ask you to save the file if you have not done this already. All the
commands in the editor will be carried out in the order of appearance.
5. Save the file and run it by typing its name at the prompt in the Command Window. Make sure
that the file is in the current folder or there is a path to the folder where the file is saved. The file
names and variable names in MATLAB must not start with a number, and must not contain special
symbols except for the underscore symbol. For example, your file can be named lab4_Q2.m.
Then by typing lab4_Q2 at the » prompt, MATLAB will run the code within.
There is yet another way to execute a part of your code. A section in the code can be executed on
its own from the icon indicated in Figure 1.2. A section is delineated by a double percentage symbol
1
This may differ in newer releases of MATLAB.
CHAPTER 1. GETTING STARTED 3
followed by a space, ‘%% ’. By placing the cursor within the section and pressing the Run-Section
icon, MATLAB will run the code from the beginning of the section to the next section or the end of the
code, whichever it encounters first.
If you want to stop your code running, press Control-C in the Command Window.
Further on you can use the various options in the Help menu.
1.2.4 Tips
The ‘Mantra’: Start your code by clearing the MATLAB memory (the workspace) using clear, closing
previously opened figures using close all, and clearing the Command Window using clc. The three
lines are shown in Figure 1.2 and reproduced here for ease of reference.
clear % Clear MATLAB Workspace Memory
close all % Close all Figures and Drawings
clc % Clear MATLAB Command Window History
Storing the Content of the Command Window: MATLAB command diary <file_name.txt>
dumps the content of MATLAB Command Window in the file with the specified name, in ASCII text
format. All subsequently typed commands and MATLAB answers will be stored there. To end the
recording of the MATLAB window dialogue, type diary off at the Command Window prompt.
Error Messages: MATLAB displays errors in the Command Window, in red. Always read the error
message. It is often a spot-on indication of what is wrong.
2. Use consistent naming conventions for variables, constants, functions and script files.
4 CHAPTER 1. GETTING STARTED
3. Use consistent indentation as provided by the MATLAB editor window. (Highlighting the text
with the cursor and choosing Text Smart Indent will reflow your script automatically, or use the
shortcut ctrl + I on Windows / + I for OS X.
4. Split your code into readable pieces. Use functions and separate script files where necessary.
5. Limit the creation of unnecessary variables in your code. Aim at minimum script length with
maximum simplicity and clarity.
6. Where suitable, use variables instead of hard-coded values as loop limits and array sizes. This
will make your code re-usable.
7. When you feel that things are getting out of control, start over.
You can type numerical expressions directly at the Command Window prompt and receive the answer
after pressing Enter. For example, type the expression below at the Command Window prompt followed
by Enter. The answer will be shown in the Command Window, as well as stored in a variable ans.
(Note: ans is replaced by the result of each expression that is not already assigned to a variable.)
The default display precision of MATLAB is 4 decimal places but the numbers are stored in memory
with a much greater precision (double precision, 64-bits/17 significant figures).
The following list of operations can be used to convert real numbers into integers:
MATLAB operations may be applied to matrices as well. All operations which are done element-
by-element, for example addition, subtraction and multiplication by a number, have the same syntax
for both scalars and matrices. The same holds for the trigonometric functions, the logarithm and the
exponent. For the multiplication division and power, the matrix operation may be interpreted in two
ways. Hadamard product denotes an operation where the matrices are of the same size, and the
entries of the resultant matrix are the pairwise products of the elements of the two matrices. MATLAB
uses ∗ for ‘proper’ matrix multiplication, and .∗ for the Hadamard product. The same holds for division
and powers. Element-wise operations are preceded by a dot, for example, ‘.∗’, ‘./’ and ‘.ˆ’.
1.4 Exercises
1. Create a standard template for your lab scripts. Put in the heading your name, username and
the module title. Save the file with name
labXX_<NameSurname>_<ddmmyy>.m
inserting your name and today’s date. When you run it, the code should clear the memory and
the Command Window, and should close any currently open figures.
2. Using only the MATLAB Command Window, find out what the command imagesc does.
n
5. The short-cut calculation for the binomial coefficient k is:
k terms
z }| {
n n × (n − 1) × (n − 2) × ...(n − k + 1)
=
k k × (k − 1) × (k − 2) × ... × 2 × 1
13
10
Using the short-cut calculation, evaluate 4 5 and verify your answer using MATLAB command
nchoosek.
6. Verify that the exponent (exp()) and natural logarithm (log()) are inverses of one another
(cancel one another).
7. Without using the square root (sqrt()) or the power command (^) find the square root of 555
with precision 4dp. To back your solution, copy the Command Window dialogue. You should save
both your typed commands and the MATLAB responses.
within the interval [2, 4]. You are not allowed to plot the function and gauge the answer from
the graph. Give the solution with precision 2dp. To document your solution, copy the Command
Window dialogue. You should save both your typed commands and the MATLAB responses.
Chapter 2
Variables and constants (scalars) in MATLAB do not have to be declared at the beginning of the code
as in other languages. Values can be assigned to them in a straightforward assignment operation, for
example,
my_first_MATLAB_variable = -1.23456789;
m = 12;
string_example = ’My first MATLAB string’;
raining_tomorrow = true;
MATLAB will create four variables and store the values in memory. The variables can be seen in the
Workspace window of the MATLAB environment.
The semicolon at the end of the assignment operation suppresses the output in the Command Window
but has no effect on the assignment itself. You can display the value of any existing variable by typing
its name at the MATLAB prompt in the Command Window. For example, typing m will return 12,
and typing raining_tomorrow will return 1. MATLAB stores true values as 1 but will accept any
non-zero value as ‘true’; a 0 value is used for ‘false’.
A neater way to display a string or the content of a variable in MATLAB Command Window is the
command disp. This command takes only one argument, which evaluates to a number or a string.
For example,
>> x = 9;
>> disp(’The value of x is:’)
>> disp(x)
7
8 CHAPTER 2. MATLAB: THE MATRIX LABORATORY
MATLAB has several predefined constants that can be used in place of variables or values in
expressions. The following is a small selection of some of the most useful ones:
pi π
√
i Imaginary number −1.
eps The smallest number, ε, determined by machine precision.
Inf The largest number, ∞.
NaN Not a Number. Undefined numerical result.
When choosing a variable name, it is best to avoid words which could be MATLAB commands or
reserved words such as: if, end, for, try, error, image, case, plot, all, and so on. If you do this, you
will (temporarily) erase the MATLAB command of the same name which you may need later in your
code.
Interestingly, variables which are used for loop indices are often chosen to be i, j or k. This convention
is probably a FORTRAN legacy where variables holding integer values must have names starting with
one of the letters I, J, K, L, M or N. FORTRAN variables starting with any other letter are understood
to be ‘real’ or floating point numbers. There is no such convention in MATLAB.
2.2 Matrices
>> A = [6 3; 5 2; 4 1];
A =
6 3
5 2
4 1
The semicolon serves as ‘carriage-return’, separating the rows of A from one another.
The size of a matrix A can be found using size(A). For a scalar, the size command will return an
array with two values: 1 (number of rows) and 1 (number of columns). For matrix A, the MATLAB
answer will be 3 and 2.
>> size(A)
ans =
CHAPTER 2. MATLAB: THE MATRIX LABORATORY 9
3 2
Vectors are matrices where either m = 1, n > 1 (vector-row) or m > 1, n = 1 (vector-column). Matrices
may have third, fourth dimension, and so on. For example, images can be represented as three panels
for the red, green and blue colours, respectively. Each panel is a matrix of m rows and n columns
of pixels. Hence an image is a 3-dimensional matrix1 of size m × n × 3. Matrices can be indexed
(or subscripted in MATLAB terms) just like in other programming languages, except that in MATLAB,
indices begin at 1. Figure 2.1 shows a parallel between array access in Java and in MATLAB.
-jArray[0] -jArray(1)
-jArray[1] -jArray(2)
-jArray[2] -jArray(3)
jArray[0][3] jArray(1,4)
jArray[0][4][2] jArray(1,5,3)
Figure 2.1: Illustration of MATLAB Matrix Dimensions. (Recreated from the MathWorks’ image.)
1
Described in more detail later, in Section 8.1.2.
10 CHAPTER 2. MATLAB: THE MATRIX LABORATORY
Alternatively, two-dimensional matrices can be indexed with only one index which goes from 1 to m×n.
Consider a vector-column constructed by putting the consecutive columns of the matrix underneath the
previous column. For example, arranging A this way will result in, the vector-column [6, 5, 4, 3, 2, 1]T .
Therefore, A(5) would return the value 2.
One of the main assets of MATLAB is that a set of elements in a matrix can be addressed simultaneously.
For example:-
>> A([1 4 5])
ans =
6 3 2
Elements in a matrix can be addressed through logical indexing. We’ll come back to this method in
Section 3.1. Consider here the following example involving matrix A above. First, create a matrix L
of the same size as A, containing logical values. Addressing A with L, as A(L) will extract only the
elements of A where L contains a true value.
>> A(L)’
ans =
6
5
2
A value can be assigned to an element of a matrix by the simple assignment operator, for example;
>> A(3,1) = -9
A =
6 3
5 2
-9 1
MATLAB will also allow assignment of multiple values in one operation. For example, to replace the
elements addressed through L by value 25, we can use:
>> A(L) = 25
A =
25 3
25 25
-9 1
CHAPTER 2. MATLAB: THE MATRIX LABORATORY 11
Better still, you can use three different values to replace the addressed elements. For example:-
>> A(L) = [55,111,222]
A =
55 3
111 222
-9 1
In addition, you can extract the desired elements in any order and with any number of copies. For
example, take two copies of element #6 followed by three copies of element #1.
>> A ([6 6 1 1 1])
ans =
1 1 55 55 55
See Chapter 8 for more detailed information, examples and exercises dealing with images and
visualising matrices.
A B C D
1 2 7 8 1 2 1 2 7 8
3 4 9 10 3 4 3 4 9 10
5 6 5 6 5 6 0 0
7 8
9 10
A matrix can be used as a ‘tile’ to form a repeated pattern using the repmat command. For example,
let A be a 2×3 matrix. The code below uses A as a tile and repeats it in 3 rows and 2 columns.
12 CHAPTER 2. MATLAB: THE MATRIX LABORATORY
>> B = repmat(A,3,2)
B =
0 1 2 0 1 2
-2 -1 0 -2 -1 0
0 1 2 0 1 2
-2 -1 0 -2 -1 0
0 1 2 0 1 2
-2 -1 0 -2 -1 0
A matrix can be reshaped using the reshape command. The new matrix must have exactly the same
number of elements. The way this command works is illustrated in Figure 2.3.
A = [1 2 3 4 concatenate
5 6 7 8 (column-by-column)
9 10 11 12] B
1
B = reshape(A,6,2) 5
A 9 1 3
2
6 5 7
1 2 3 4
number of rows 10 9 11
5 6 7 8
(new matrix)
3 2 4
9 10 11 12 7
11 6 8
4 10 12
8
number of columns
12
(new matrix)
Notice that the input matrix is first concatenated into a vector-column, taking consecutive columns
and placing them underneath the last. The output matrix is constructed column by column, taking
consecutive values from the vector-column.
If a square matrix is required, one input argument will suffice, for example, ones(3). This is both the
number of rows and the number of columns. The identity matrix is square by definition, hence eye()
CHAPTER 2. MATLAB: THE MATRIX LABORATORY 13
only takes one input argument. Otherwise, the matrix is created with the specified number of rows
and columns. These matrices can be generated in more than two dimensions.
In the matrix with random numbers, all values are drawn independently from a uniform random
distribution in the interval [0,1].
The three components of the colon operator do not have to be integers, nor must they be positive. For
example;
>> y = -1.7:0.81:2.452
y =
-1.7000 -0.8900 -0.0800 0.7300 1.5400 2.3500
The vectors generated by the colon operators are row-vectors. The vector contains as many elements as
necessary to increase the start value by the increment value to reach the end value without exceeding
it. For example:-
>> 1:10:55
ans =
1 11 21 31 41 51
Matrices can be addressed with vectors created by the colon operator. The vector can be embedded
directly as the index;
>> x = 2:4:20;
>> Y = [x;2*x]
Y =
2 6 10 14 18
4 12 20 28 36
>> Y(1,2:4)
ans =
6 10 14
In this example, the addressed values are in row 1, and columns 2, 3 and 4.
One particularly useful form of the colon operator is for defining the whole range within a matrix
dimension. For example, Y(:,2) will return all elements in column 2 of Y . In this case, ‘:’ means ‘all’
(rows):
14 CHAPTER 2. MATLAB: THE MATRIX LABORATORY
>> Y(:,2)
ans =
6
12
The colon operator on its own, A(:), reconfigures matrix A into a column vector by placing each
column below the last. For example;
A =
9 6 3
8 5 2
7 4 1
>> A(:)
ans =
9
8
7
6
5
4
3
2
1
>> x = linspace(0,1,7)
x =
0 0.1667 0.3333 0.5000 0.6667 0.8333 1.0000
Sometimes we need to generate all (x, y) coordinates of the points on a grid. Suppose that the grid
spans the interval from 2 to 12 on x and has 4 points, and the interval from −1 and 6, and has 5
points on y. The meshgrid command can be used for generating simultaneously the x and the y
coordinates:
CHAPTER 2. MATLAB: THE MATRIX LABORATORY 15
y =
-1.0000 -1.0000 -1.0000 -1.0000
0.7500 0.7500 0.7500 0.7500
2.5000 2.5000 2.5000 2.5000
4.2500 4.2500 4.2500 4.2500
6.0000 6.0000 6.0000 6.0000
Try the following example with the meshgrid and linspace commands.2
clear all; close all; clc
[x,y] = meshgrid(linspace(2,12,4), linspace(-1,6,5));
figure, hold on, grid on % open and hold a figure with a grid
surf(x,y,x.*y) % plot the surface of function x*y
surf(x,y,zeros(size(x))) % plot the plane of the zero-"ground"
stem3(x,y,x.*y,’k*-’) % plot stems at all grid points from ground to surface
rotate3d % allow for rotation of the figure with the mouse
Figure 2.4 shows the MATLAB output for the above piece of code. Using the mouse, you can rotate the
plot in the MATLAB figure.
2
Plotting will be detailed later in Chapter 5.
16 CHAPTER 2. MATLAB: THE MATRIX LABORATORY
Command Return
a’ Transpose of a
find(a) Indices of all non-zero elements in a.
fliplr(a) Matrix a, flipped horizontally
flipud(a) Matrix a, flipped vertically.
inv(a) Inverse of a
min(a) Minimum-valued element of a. †
max(a) Maximum-valued element of a. †
numel(a) The number of elements of a.
repmat(a,m,n) A matrix where matrix a is repeated in m rows and n columns
reshape(a,m,n) Matrix a reshaped into m rows and n columns.
size(a) The size of a (#rows, #columns, ...)
sort(a) Vector a sorted into ascending order. †
sum(a) Sum of elements of a. †
unique(a) The list of unique elements of a in ascending order.
† For a matrix, the operation will be carried out separately on each column. For a vector (row or column), the
operation will be carried out on the vector.
In addition to the minimum or maximum values returned by the respective commands, MATLAB returns
the exact index where this value has been encountered. For example,
a = [3 1 9 5 2 1];
m = max(a)
CHAPTER 2. MATLAB: THE MATRIX LABORATORY 17
MATLAB will return 9 in m and 3 in i because a(3) holds the largest value 9. Recent versions of
MATLAB (after 7.9, 2009b) allow for replacing unnecessary arguments with a tilde (∼). If only the place
of the maximum is of interest, you can use:
[~,i] = max(a)
If a minimum or a maximum value appears more than once in the array, only the index of the first
occurrence will be returned. In the example above, the minimum value 1 sits in positions 2 and 6. Only
2 will be returned as the second output argument of the min command.
Similarly, the sort command returns as the second argument a permutation of the indices
corresponding to the sorted vector. For example,
>> [s,p] = sort(a)
s =
1 1 2 3 5 9
p =
2 6 5 1 4 3
In this example, s contains the sorted a. p(1) is 2 because the first occurrence of the minimum
element 1 is at position 2. The next smallest element is the 1 at position 6, hence the second entry in
p. The third smallest element, 2, is in position 5, and so on.
The element is returned as a cell. If you want to access the content of the cell, use braces { } instead
of parentheses ( ):
18 CHAPTER 2. MATLAB: THE MATRIX LABORATORY
>> C{2,1}
ans =
0 0 0
0 0 0
0 0 0
2.7 Exercises
1. Create a 4 × 1 column vector, that contains any values of your choosing.
2. Create a cell array of 8 elements such that element i contains the identity matrix of size i,
i = 1, . . . , 8.
3. Use one MATLAB command to evaluate the sine of 30o , 45o , 60o , and 120o . Subsequently, evaluate
cosine, tangent and cotangent of the same angles.
(ABC )T = C T B T AT ,
where A, B and C are matrices of different sizes, and the product ABC is feasible.
8. Create a 1 × 6 vector v containing the integer values from 20 to 25. Subsequently, create an
1 × 6 vector whose values are equal to 5 times the values in v.
10. Create a vector spanning the range from 0 to 2π, containing 100 equally spaced components, so
that the first value is 0, and the last value is 2π.
(a) Rescale q into a unit vector (magnitude 1) using only the matrix operations shown in
Tables 2.1 and 2.2.
(b) Rescale q linearly, so that the minimum is 0 and the maximum is 1 - again using only the
matrix operations presented in this chapter.
CHAPTER 2. MATLAB: THE MATRIX LABORATORY 19
(c) Rescale q linearly, so that the minimum is −3.6 and the maximum is 105 - using the same
functions/operations.
12. Create a matrix of 100 rows and 100 columns. The odd columns should contain values 2, and the
even columns, values 0.
13. Create the following matrix using one MATLAB line of code and the reshape command.
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
M =
8 8 8 8 8 8 8 8 8 8
8 8 8 8 8 8 8 8 8 8
8 8 0 0 0 0 0 0 8 8
8 8 0 0 0 0 0 0 8 8
8 8 0 0 3 3 0 0 8 8
8 8 0 0 3 3 0 0 8 8
8 8 0 0 0 0 0 0 8 8
8 8 0 0 0 0 0 0 8 8
8 8 8 8 8 8 8 8 8 8
8 8 8 8 8 8 8 8 8 8
15. Write MATLAB code to construct matrix B whose image is shown in Figure 2.5. Subsequently,
reproduce the two plots in the figure.
16. Write MATLAB code to construct the matrices described below and visualise them using
imagesc. Do not use loops!
20 CHAPTER 2. MATLAB: THE MATRIX LABORATORY
(a) The first matrix should have 16 rows with consecutive integers from 1 to N, where N is
given by the user when prompted. The rows should be alternating: the numbers should be
in increasing order in row 1, decreasing order in row 2, increasing in row 3, decreasing in
row 4 and so on. An example for N = 20 is shown in Figure 2.6 (a).
(b) The second matrix should be of size 10 by 10. The exact colour of the blocks does not matter
as long as all 4 colours are different and the colour of the central blocks are the same. An
example is shown in Figure 2.6 (b).
(c) The third matrix should appear as a colour frame of size M (M rows and M columns), where
M is given by the user, when prompted. An example for M = 10 is shown in Figure 2.6 (c).
17. Knowing that for any square matrix A, B = A + AT is a symmetric matrix; reproduce the four
plots in Figure 2.7. Save the four matrices in a cell array.
18. Using a matrix equation, find the intersection point of the lines defined by the following equations:
7x − 12y + 4 = 0
12x − 45y + 26 = 0
19. Run the code below. It will take an image available from the standard MATLAB installation,
convert it to grey scale, store the matrix in variable im, and show the image as in Figure 2.8 (a).
im = rgb2gray(imread(’pepper.png’)); % read the image into a 2d matrix
imshow(im) % show the grey-level image
(a) Find out the size of the matrix containing the image, and cut (approximately) the part that
contains the onion. Use the imshow command to display the result as in Figure 2.8 (b).
You must not use any image processing methods and commands such as ‘crop’.
If you are unsure whether a command is from the Image Processing Toolkit, type which
<command> in the Command Window. The result will show the path to the m-file where
that command is defined. If the path contains ‘toolbox/images’ the command is excluded.
(b) Add a frame of k rows and k columns of zero values around the onion image and display
it, as shown in Figure 2.8 (c). The value of k should be changeable; in the example, k = 30.
Note: When displaying your new matrix, say z, use:
imshow(uint8(z)) % show the grey-level image
(c) Find out how many different grey level intensities (of the possible 256 intensities) appear
in your onion image. Compare this with the number of intensities in the original image and
give a short comment.
20. Create a matrix A of size m × n, whose elements a(i, j) are calculated from the row and column
indices as follows:
a(i, j) = (j − 4)2 (i + 1)−3 + ij .
The parameters m and n should be changeable. (You are not allowed to use loops here. Recall
the command ‘meshgrid’.)
21. Create vectors x and y, which, when plotted and joined, will show the pattern in Figure 2.9 (a)-(c).
22. Create vectors x and y, which, when plotted and joined, will show the pattern in Figure 2.9 (d)-(f).
22 CHAPTER 2. MATLAB: THE MATRIX LABORATORY
3 8 1
0.8
6
2
0.6
4
y
y
0.4
1
2
0.2
0 0 0
0 10 20 30 0 0.5 1 0 5 10 15 20
x x x
4 40 1
0.8
3 30
0.6
y
2 20
0.4
1 10
0.2
0 0 0
0 5 10 0 10 20 30 0 10 20 30
x x x
3.1.1 Representation
A logical expression is one that evaluates to either true or false. For example, v > 0 is a logical
expression that will be true if the variable v is greater than zero and false otherwise. Logical expressions
can be assigned to Boolean variables. For example, s = v > 0 stores the value of the logical expression
v > 0 in a Boolean variable s. Some programming languages use special data types, as shown in
Table 3.1. These are generally referred to as Boolean data types. Other languages, such as MATLAB,
allow general data types to represent logical answers.
Logical expressions may contain numerical, logical and relational operations. Numerical operations
involve numbers and their result is a number. Relational operators compare two numbers and their
result is true or false. Finally, logical operations connect two logical variables. The result is again,
true or false. Table 3.2 shows the most often used relational and logical operations as well as their
MATLAB syntax.
23
24 CHAPTER 3. LOGICAL EXPRESSIONS AND LOOPS
Relational operations
a == b # which are equal to one another.
a ~= b # which are not equal to one another.
a <= b # where a(i) is less than or equal to b(i).
a < b # where a(i) is strictly less than b(i).
a >= b # where a(i) is greater than or equal to b(i).
a > b # where a(i) is strictly greater than b(i).
Logical operations
a & b # which are both true (non-zero).
a && b Valid only for scalars. True if both are true.
a | b # where either one or both of a(i) and b(i) are true (non-zero)
a || b Valid only for scalars. True if any or both are true.
xor(a,b) # where one of a(i), b(i) is true and the other is false.
~a True if a is false. Also known as ‘not’ a.
For example,
>> a = [ 0 1 2 2 3 1 0 0 1 0];
>> b = [-2 5 0 0 4 1 0 6 3 0];
>> a&b
0 1 0 0 1 1 0 0 1 0
and
>> xor(a,b)
1 0 1 1 0 0 0 1 0 0
Notice that logical operators join two Boolean variables while relational operators join two
numerical expressions. In a logical expression, numerical operations are carried out first, then the
relational operations, and finally the logical operations. The sequence of operations is illustrated in
Figure 3.1.
Of course, if parentheses are present, they have precedence over any operation. The operations in the
innermost parentheses are carried out first, the operations within the next innermost, second, and so
on. If you are not sure about the order of operations, use parentheses.
CHAPTER 3. LOGICAL EXPRESSIONS AND LOOPS 25
logical
3
Therefore c contains value true
Without typing the following lines in MATLAB, try to determine the answers for the three logical
expressions:
>> a & b % 1
>> a ~= b % 2
>> a - b > 3 % 3
Next, we can select the relevant elements of A and assign the desired value:
>> A(index) = 22;
In fact, the whole assignment can be done using just one statement:
>> A(A<0) = 22;
Any logical expression that evaluates to a true/false matrix of the same size as that of a matrix A, can
be used as a logical index into A.
26 CHAPTER 3. LOGICAL EXPRESSIONS AND LOOPS
Table 3.3 contains details of some commonly used logical functions in MATLAB.
Command Return
all(a) True if all elements of a are true/non-zero.
any(a) True if any element of a is true/non-zero.
exist(a) True if a exists in the MATLAB path or workspace
as a file, function or a variable.
isempty(a) True if a does not contain any elements.
ismember(a,b) True if b can be found in a.
Conditional operations act like program switches which respond to certain conditions within the
program. The basic if and switch constructs are shown in Figure 3.2.
optional
Figure 3.2: Syntax of the ‘if’ and ‘switch/case’ operators. The shaded parts are optional.
Using the MATLAB command rand generate a random number between 0 and 1. If the number is
greater than 0.5, display the word ‘lucky’, otherwise display ‘unlucky’.
CHAPTER 3. LOGICAL EXPRESSIONS AND LOOPS 27
Ask the user to input an integer number between 1 and 4, then display the number as a word.
var is the name of the counter variable. var will take consecutive values starting with start_value
and proceeding with start_value +1, start_value +2, and so on, until end_value is reached,
but not exceeded. For example, let start_value = 1 and end_value = N. In this case, var will
take consecutive values 1, 2, 3, ... N. The last iteration will be at var = N because N + 1 exceeds
end_value.
The loop variable does not have to be an integer. Consider the fragment;
for w = -0.8:4.1
Start
Start
i=1
N
Y Expression End
i > N? End true?
N Y
Loop Loop
statements statements
i=i+1
There will be only 5 iterations of this loop because 3.2 + 1 = 4.2 exceeds the end_value of 4.1.
The loop variable does not have to be a number either. Consider the following example:
for t = ’a’:’h’
disp(t)
end
The loop will display a column of the lower-case letters from ‘a’ to ‘h’.
The default increment of the loop variable is 1. We can specify a different increment value, just as with
the colon operator. For example,
for w = 6.2:3.1:10.7
will run through the loop statements twice, for values of w 6.2 and 9.3. The next value of w would be
9.3 + 3.1 = 12.4, which exceeds the end_value of 10.7.
With the functionality offered by the colon operator, the for loop can run ‘backwards’. This
fragment,
for k = 12:-2:-4
will run through the loop statements 9 times, for these values of k: -
12 10 8 6 4 2 0 -2 -4
If matrix is a vector, var takes each subsequent value from the vector. For example,
for v = [2 4 6 8 10 6 6 6 14]
disp([repmat(’ ’,1,18-v),repmat(’.’,1,2*v)])
end
will plot a little house made of dots, in the MATLAB Command Window.
3.5 Examples
Solution. Suppose that there are N elements to sort. Organise a loop which goes from 1 to N − 1.
Naturally, the loop does not have to go to N because, once N − 1 values are sorted, so is the last
one.
In each pass through the loop, one value will be placed in its destination. The first pass will identify
the largest element and place it at the top of the array. The second largest element will be identified
in pass 2, and will replace the second element of A. Thus, at iteration i, we will be positioning an
element at i in A.
To identify the largest element, set a variable to the smallest value MATLAB can handle, -Inf. Search
through the unsorted part of the array by comparing the current maximum with the array entry. If
array entry is larger, store the value as the new maximum, and the index where this maximum value
is found.
1
This algorithm identifies the largest element of the array and places it first, then the second largest, and places it second,
and so on until the smallest element is placed last in the array.
30 CHAPTER 3. LOGICAL EXPRESSIONS AND LOOPS
Note how easy it is to swap two elements in an array in MATLAB: A([i index_max]) =
A([index_max i]);. If another language was used, we first need to save the content of one of the
cells in a temporary variable, for example, temp = A(i); Then the ith entry can be replaced as A(i)
= A(index_max);. Finally, the saved value should be placed in the array as A(index_max) =
temp;.
To show the work of the code, use the following command to generate A: A = rand(10,2);.
Solution. The loop may go through just the three top rows of A and complete the task, or through the
whole of A and still not find three rows satisfying the condition. The code is shown below.
A = rand(10,2);
rc = []; % set of the indices of the rows where A(i,1) > A(i,2)
i = 1; % index counter for A
while numel(rc) < 3 && i <= size(A,1)
if A(i,1) > A(i,2)
rc = [rc,i]; % store the found row
end
i = i + 1; % increment the index for A
end
if i == size(A,1)+1 && numel(rc) < 3
CHAPTER 3. LOGICAL EXPRESSIONS AND LOOPS 31
Notice how much easier the solution becomes if we use matrix operations (vectorising):
A = rand(10,2);
rc = find(A(:,1) > A(:,2)); % rows of interest
if numel(rc) < 3
disp(’A set of three rows was not found’)
else
disp(rc(1:3))
end
3.6 Exercises
1. Without running MATLAB, evaluate b1 to b6 in the following sequence of expressions:
2. Find and display all integers between 1 and 10000 which divide by 37. Propose at least two
different ways to solve this problem.
3. Load up and show MATLAB’s image ‘coins.png’ (Figure 3.4 (a)) using the following line:
z = imread(’coins.png’); figure, imshow(z)
This will enter a matrix z in MATLAB’s memory. Values close to 0 correspond to dark, and values
close to 255, to light pixels. Propose and implement a simple way to replace the background of
the image with white, similar to the image shown in Figure 3.4 (b).
4. Similarly to the previous problem, upload image ‘peppers.png’ (Figure 3.5 (b)) using
z = rgb2gray(imread(’peppers.png’)); figure, imshow(z)
32 CHAPTER 3. LOGICAL EXPRESSIONS AND LOOPS
Figure 3.4: The original coin image and the desired result.
This time, convert the image into three shades: black, grey and white, as shown in Figure 3.5 (b).
(The appearance of the image only needs to be approximately the same as it will depend on the
two thresholds which you choose.)
Figure 3.5: The original peppers image and the desired result.
5. Fibonacci numbers form a sequence starting with 0 followed by 1. Each subsequent number is
the sum of the previous two. Hence the sequence starts as 0, 1, 1, 2, 3, 5, 8, 13, ... Calculate and
display the first 10 even Fibonacci numbers.
6. Figure 3.6 shows 8 scatterplots in 2d. Suppose that you are given the coordinates of a point
(x, y). For each scatterplot, write a single logical expression which will yield TRUE if the point
is in the black region and FALSE, otherwise.
7. Ask the user to input an integer in the range from 10 to 500. (Look up and use the input
command.) If the input number is not an integer or is outside the limits, keep asking for a new
number. Store the number in a variable N.
8. Write MATLAB code for the ‘Guess My Number’ game. First, the computer picks a random integer
between 1 and 10 using the randi command. Next, the user is asked to enter their guess. If
the guess matches the chosen number, display a congratulations message. Otherwise, display a
‘better luck next time’ message.
CHAPTER 3. LOGICAL EXPRESSIONS AND LOOPS 33
9. Simple Image Filter. Load up and show MATLAB’s image ‘gantrycrane.png’ using the following
line:
z = rgb2gray(imread(’gantrycrane.png’)); figure, imshow(z)
Create a new image where every element of matrix z is replaced by the minimum of its
neighbourhood values. The neighbourhood includes the central element and the surrounding
8 elements. Exclude the top and bottom rows of elements, as well the left and the right edges.
Use nested loops. Repeat the process, but this time replace the value with the maximum within
the neighbourhood. The resultant images should look like the ones in Figure 3.7.
10. Consider a grid of size n × m with virtual bugs. Each bug lives in a grid cell. An example of the
grid for n = 20 and m = 30 is shown in Figure 3.8. The grid is given to you in a form of a matrix
A of size m × n, with 0s in the empty cells and 1s in the cells occupied by bugs.
(a) Find out the average number of neighbours per bug. Neighbours are considered to be the
bugs in the 8 surrounding cells.
(b) MATLAB includes a version of Conway’s Game of Life. It is started by typing life in the
command window. The rules are as follows:2
• Any bug with fewer than two neighbour bugs dies from isolation.
• Any bug with two or three neighbour bugs lives on to the next generation.
• Any bug with more than three neighbour bugs dies from overcrowding.
• Any empty cell with exactly three neighbour bugs becomes a bug, as if by reproduction.
• The rules apply in the same way to the edge and corner cells even thought they have
fewer physical neighbour cells.
Using these rules, calculate the next generation of bugs for your randomly populated grid.
(c) Use the command spy to see the grid. Include it in a loop where you evolve the population
with each pass, visualise it with spy, and pause the execution with command pause(0.2).
2
http://en.wikipedia.org/wiki/Conway’s_Game_of_Life
CHAPTER 3. LOGICAL EXPRESSIONS AND LOOPS 35
Run your code from the previous sub-problem to evolve the ‘glider gun’ population whose
starting layout and the first five generations are shown in Figure 3.9.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
1
2
3
4
5
6
7
8
9
10
11
Figure 3.9: The glider gun’s initial configuration and first five generations.
3
http://commons.wikimedia.org/wiki/File:Game_of_life_glider_gun.svg
Chapter 4
Functions
Functions are useful when a certain part of the code must be repeated many times or if we want to
make it into a basic tool available for future use.
4.1 Syntax
Functions in MATLAB are stored in separate files. Unless specifically declared as global, all variables
are local, which means that they are valid only within that function. Think about a function as a
‘watertight’ piece of code. Its communication with the outside world are the input and the output
variables.
Neither of the lists is compulsory. If there are output arguments, they must receive values in the body
of the function. An interesting property of MATLAB functions is that not all input and output arguments
need to be assigned in the call. For example, consider a one-dimensional array A.
Replacement of the output argument by a tilde was introduced fairly recently (2009b, MATLAB Version
7.9). Until then, a dummy variable had to be used in its place.
A call to fu is made in the MATLAB script and the output is assigned to variable m. The function is
stored in a separate file of the same name (fu.m). It returns two outputs: the sum of the three input
arguments and their product. As the function is called with one output argument only, it will return in
m the sum 4 + 2 + 1 = 7.
36
CHAPTER 4. FUNCTIONS 37
4.2 Naming
A call to a function will look for a file with the function’s name in the MATLAB path. Therefore, it makes
sense to set the file name and the function name to be the same. For example, if your function is called
draw_trapeze but the file is named trapeze.m, MATLAB will not accept a call to draw_trapeze.
It will, however, accept a call to trapeze.m, and will subsequently run file trapeze regardless of
the name you have specified as the function declaration within the file (draw_trapeze).
In this example, the script calls function fu2. Function fu2 will be visible to MATLAB while function
fu will not. Function fu is accessible only within fu2. Function fu2 returns two output arguments.
In p, it stores the sum of the three input arguments divided by their product, if the product is not zero.
If the product is zero, an empty value is returned (p = []). The second output argument, q, is the
sum of the sum and the product of the three inputs. In this example, only second argument of fu2 is
requested by the MATLAB script, therefore we store in s 4 + 2 + 1 + 4 × 2 × 1 = 15.
Multiple functions are particularly useful for writing graphical user interface (GUI) code.
From this point onwards, you can use fu(arg), where the argument can be a single number or an
array. (The array operations are accounted for by using ‘.*’ instead of just ‘*’, and ‘.^’ instead of ‘^’.)
For example,
figure, plot(0:.3:20,fu(0:.3:20)), grid on
will open up a figure and plot the value of the function f (x) = x sin(x) − exp(−x 2 ) for x ∈
{0, 0.3, 0.6, 0.9, 1.2, . . . , 19.8}.
In the function definition, instead of a single x, we can use a list of arguments after the @ sign
(@(list_of_arguments)). For example,
fu = @(p,q) p.^q - 2*(p-q);
4.5 Recursion
As many other programming languages, MATLAB allows recursion, which means that a function
can call itself. Recursion usually leads to very elegant code but this does not offer computational
advantage.
Only a small number of iterative algorithms can be solved using recursion. An example is the bisection
algorithm for finding a zero of a function within a given interval. Consider the function
There is one zero of the function in the interval [1,2]. Find the zero x ∗ , such that f (x ∗ ) ≈ 0, with
precision1 ε = 10−6 . This means that an interval with centre x ∗ and length ε contains the true point
where f (x) crosses the x-axis.
1. Input the precision ε, the function f (x) and the bounds a and b of the interval containing the
zero.
(b) else, if f (a)f (m) < 0 (the zero is in [a, m]) call the function with interval [a, m], else call the
function with interval [m, b].
The following script calls function bisection for equation function f (x) = sin 2x exp x − 4 (LHS of
the equation) and interval [1, 2] with precision 10−3 :
e = 10^-3; % precision
f = @(x) sin(2*x) * exp(x-4); % equation LHS
xstar = bisection(e,f,1,2);
disp(xstar)
The MATLAB output is 1.5708. If you substitute 1.570 and 1.571 for x, f (x) should have function values
with different signs.
4.6 Exercises
1. Write a MATLAB function for calculating the Euclidean distance between two points in the n-
dimensional space. The points are given as the input arguments a and b. Both should be arrays
1
The word ‘precision’ here is used to denote the length of the interval containing the solution. This may differ from the
meaning of this word in other contexts.
40 CHAPTER 4. FUNCTIONS
with n elements. It should not matter for your function whether either input is a row or a column.
Demonstrate the work of your function by an example.
2. Write a MATLAB function for calculating the Euclidean distance between two two-dimensional
arrays A and B given as input arguments. A is of size N × n, and B is of size M × n. The function
should return a matrix D of size N × M where element d(i, j) is the Euclidean distance between
row i of A and row j of B.
3. Write an inline function that will calculate 6x − 4y + xy + cos2 (x − k). Assume that x and y may
scalars, vectors or matrices and that all operations should be carried out element-wise.
4. Write a MATLAB function for checking if a given point (x, y) is within the square with a bottom
left corner at (p, q) and side s. The input arguments are x, y, p, q and s, and the output is either
true (the point is in the square) or false (the point is not in the square).
5. Write a non-recursive MATLAB function to calculate the Fibonacci sequence and return the
number with a specified index, for example, the 4th number in the series (this number is 5).
6. Write a recursive MATLAB function to calculate the Fibonacci sequence and return the number
with a specified index.
7. Write a short MATLAB function to find out whether a given number (up to 1,000,000) is a prime
number. The function should return true or false. Bear in mind that 1 is not considered a prime
number. (Hint: Use the brute force approach and divide the number (K ) by all integers from 2
to K-1. Check the remainders for 0s.)
Subsequently, apply this function to list all prime numbers between 1 and 100.
8. Write your own function for the bubble sort algorithm and demonstrate its work.
Chapter 5
Plotting
5.1 Plotting Commands
5.1.1 Plot
The plot command is easily one of the most useful MATLAB commands. It needs at least one argument
as shown in Figure 5.1. If there is no open figure, MATLAB will open a new one and will plot the
argument (an array) versus its index. If there are two arrays as input arguments, MATLAB will take
the first array to be the x-coordinates, and the second array, the y-coordinates.
A third string argument can specify the type of line, colour and marker of the plotted line. The three
figures in the example in Figure 5.1 are shown in Figure 5.2.
If you want to plot more than one thing on the same figure, use the command hold on. The grid
lines can be toggled on and of with the command grid (use grid on).
Figure 5.3 gives some more detail about the plot command and the appearance of MATLAB
figures.
There is lot more to be learned about the plot command as shown by the examples in the next
section.
41
42 CHAPTER 5. PLOTTING
edit
title
grid
y-label
marker
line
axes x-label
5.1.2 Fill
The fill command fills a specified region with a specified colour. The syntax is:
fill(x,y,colour)
The first argument is an array with the x-coordinates of the shape to be filled, and the second argument
is an array of the same size with the y-coordinates. The third argument is either one of the pre-defined
colour strings:
or an array [a, b, c] with three numbers between 0 and 1. These three numbers make up the colour, by
mixing a amount of red of possible 1), b amount of green and c amount of blue. For example, colour
CHAPTER 5. PLOTTING 43
‘dark salmon’ is made by [0.9137, 0.5882, 0.4784]. Figure 5.4 shows three circles filled respectively with
colours dark salmon, lavender bush and maroon. The code is shown below.
figure, hold on
t = linspace(0,2*pi,50); % 50 angles from 0 to 2*pi (in radians)
fill(0.2*sin(t)+2.2,0.2*cos(t),[0.5020 0 0])
% circle centred at [2.2,0] with radius 0.2, filled with maroon colour.
grid on
axis equal
Notice two things. First, there is black outline (by default) fo all ‘fill’ objects. Second, we used command
axis equal. This makes the units on the x-axis and y-axis to become of equal size. This way the
circles looks like circles and not ellipses.
44 CHAPTER 5. PLOTTING
5.2 Examples
Reproduce the shapes and plots in Figure 5.5.
(a) Weights (b) Zigzag (c) Lightning bolt (d) Christmas tree (e) Bear’s face
Plot (a) can be constructed with one thick line and circle markers. To create the illusion of perspective,
the ball which is closer to the viewer should be larger. This can be achieved by plotting a larger circular
marker over the smaller one. The line width and the sizes of the two markers are determined by trying
out different values until the figure meets the designer’s approval. The code is shown below:
% Weights
figure, hold on, axis equal off % set up the figure and format the axes
plot([0 0.8],[0 0.3],’k.-’,’markersize’,200,’linewidth’,8)
plot(0,0,’k.’,’markersize’,250) % plot a second, larger marker
The zigzag in plot (b) is based on a repeated pattern of x coordinates, e.g., [0 1 0 1 0 1 ...], while the y
coordinate must increase as [1 1 2 2 3 3 ...]. Both patterns can be created using matrix manipulation
as shown in the code below:
% Zigzag
figure, hold on, axis equal off % set up the figure and format the axes
x = repmat([0,1],1,8); y = [1:8;1:8];
plot(x,y(:),’ks-’,’markersize’,8,’MarkerFaceColor’,’y’)
For the lightning bolt in plot (c), the fill command should be used. The shadow has the same shape
as the yellow bolt, and is displaced on both x and y. The bottom point of the shadow is ‘stretched’
to match the tip of the yellow spear. Note; that the shadow must be plotted first. The code is shown
below;
% Lightning bolt
figure, hold on, axis equal off
x = [-2 3 2 4 3 5 4 6 4,2,3,1,2,0,1,-2]; % yellow X
y = [-1 1 1 2 2 3 3 4 4 3 3 2 2 1 1 -1]*3; % yellow Y
xsh = x + 1; xsh(1) = -2; xsh(end) = -2; % shadow X
CHAPTER 5. PLOTTING 45
The Christmas tree in plot (d) is formed from two symmetrical parts. The x-values can be constructed for
one of the parts and flipped for the other part. In the code below, both x and y are constructed initially
as arrays with two rows. Then, with the help of the colon operator, the two rows are concatenated
column-by-column to make the needed sequence of vertices. For example, if x has values [0 2 4 6] in
the first row and [0 1 3 5] in the second row, the concatenated (and transposed) vector will be [0 0 2 1
4 3 6 5]. This gives the sawtooth pattern for the periphery of the tree. The code for the Christmas tree
is as follows:
% Christmas tree
x = [0:2:18;0 1:2:17]; y = [20:-2:1;20:-2:1]*3;
x = [-fliplr(x(:)’) x(:)’]; y = [fliplr(y(:)’) y(:)’];
figure, hold on, axis equal off, fill(x,y,’g’)
The Bear’s face in plot (e) would be difficult to plot with markers of different sizes. It is better to use
filled circles as shown in the code below:
% Bear’s face
brown = [0.4 0.2 0]; % colour definition
figure, hold on, axis equal off
t = linspace(0,2*pi,100);
fill(sin(t),cos(t),brown,’EdgeColor’,brown) % face
fill(sin(t)*0.5+1,cos(t)*0.5+1,brown,’EdgeColor’,brown)
fill(sin(t)*0.5-1,cos(t)*0.5+1,brown,’EdgeColor’,brown)
fill(sin(t)*0.2+0.3,cos(t)*0.4,’w’,’EdgeColor’,’w’)
fill(sin(t)*0.2-0.3,cos(t)*0.4,’w’,’EdgeColor’,’w’)
fill(sin(t)*0.1+0.28,cos(t)*0.1-0.2,’k’,’EdgeColor’,’k’)
fill(sin(t)*0.1-0.28,cos(t)*0.1-0.2,’k’,’EdgeColor’,’k’)
Random art can be created using filled polygons, not necessarily convex, with random vertices. For
example, fill(rand(10,1),rand(10,1),rand(1,3)) will create a random shape of joined line
segments, where some of the closed spaces will be filled with a random colour. Figure 5.6 shows the
output of the following piece of code:
Figure 5.6: Repetitions of a shrinking random shape filled with progressively darkening red colour.
5.3 Exercises
1. Plot the six European flags as in Figure 5.7. The names of the countries should be displayed
as well. All flags should be plotted in one figure. This task should be completed using the the
subplot command rather than adjusting spacing between the flags yourself.
2. Write a function which will draw a circle in an open figure. The input arguments are x, y, r, c;
x and y are the coordinates of the centre, r is the radius, and c is a three-element vector with
the colour. Demonstrate your function by using it to plot 30 circles at random positions, with
random radii, and with random colours, as in Figure 5.8 (a).
3. Create an art figure by plotting 10 filled squares with jagged edges as shown in Figure 5.8 (b).
The fill colours should be random. The squares should be arranged approximately as in the
example in the figure.
4. Plot a Random Art Square similar to the example in Figure 5.8 (c). There should be 20 random
forms with random colours in the square. Note that some of the forms are not contained fully
CHAPTER 5. PLOTTING 47
(a) Circles (b) Jagged edge art (c) Random art square
in the figure. Each form must have between 3 and 6 vertices. The number of vertices should be
random.
5. Create a loop to plot 10 triangles with random vertices in the unit square. Not every triangle
should be plotted. Plot only triangles which are nearly equilateral. To do this, check whether
the three edges differ by less than a chosen small constant, for example e = 0.01. The triangles
should be filled with random colours. An example of the desired output is shown in Figure 5.9 (a).
6. Write a MATLAB function which takes an integer k as its input argument and plots k filled
squares of random colours, nested as shown in Figure 5.9 (b).
7. Using the function from the previous problem, reproduce Figure 5.10. The number of squares k
varies from 3 to 12. All colours are random.
8. Plot a shape consisting of four filled polygons. The polygons are mirror versions of one polygon
with k random vertices, where k is a parameter. The figure should be symmetrical about the
x and y axes. The polygons should touch in the middle point as shown in the examples in
48 CHAPTER 5. PLOTTING
Figure 5.11 (a) (k = 10). Try to accomplish this task using matrix operations, not geometric
functions such as fliplr.
9. Write MATLAB code to produce a 4-part logo. Nine examples are shown in Figure 5.11 (b). You
can use your own design of the basic shape, or pick it at random. The top left part should be
black and the bottom right should be white. The other two colours should be chosen randomly by
your program. The four shapes should have a common edge on the x-axis and on the y-axis. The
length of each of these edges should be at least half of the span of the shape on the respective
axis.
CHAPTER 5. PLOTTING 49
(a) Create a set of 25 random shapes, each one having 6 random vertices and filled with a
random colour. Plot the shapes on a 5-by-5 grid as shown in Figure 5.12 (a). This should
not be achieved using the subplot command and can be accomplished with a single loop.
(b) Make a figure with two subplots. The first subplot should contain the original shapes, and
the second subplot should contain the same shapes, in a random order on the grid. An
example is shown in Figure 5.12 (b).
(a) Figure 5.13 (a) shows a field with randomly distributed copies of a filled small shape or
creature. The shape is random, but fixed for the figure, while the colours and the positions
of the replicas are random. Write MATLAB code to produce a similar figure.
(b) Subsequently, design a battle scene, where four ‘armies’ of creatures are distributed in four
parts of the space as shown in Figure 5.13 (b). The creatures from each army should have
the same (random) shape and colour. The positions of the creatures within the regions are
random too. (Note: The creatures are allowed to overlap near the borders.)
(a) Use a loop to create 5 diamonds as in Figure 5.14(a) (one diamond in each pass through
the loop). The innermost diamond is black, and the outermost is red. Each diamond has its
own fixed colour. The colours of the diamonds go gradually from black to red.
(b) Subsequently, use one loop to create the pattern in Figure 5.14(b). The colour goes gradually
from black to green followed by black to blue. The figure should be plotted as succession
of diamonds.
(a) (b)
14. Balloons
(a) Create a MATLAB function called draw_balloon. The function should take as its input
arguments: the x and the y coordinates of the centre, the radius r, the colour c, and the
length of the string l. The function should plot the balloon on the current axes (held and
equalised). An example is shown in Figure 5.16 (a). The function is called using the following
line:
figure, hold on, axis equal, draw_balloon(1,2,4,[0.2 0.6 0.9],7)
(b) Subsequently, write a MATLAB script to produce a figure with 20 balloons with random
colours and sizes (Figure 5.16 (b)).
(c) Finally, produce another figure with 20 random balloons, all of which have reached the
ceiling, as shown in Figure 5.16 (c).
15. Write a MATLAB function called ‘dice’. The function should open a figure and display the given
face of a regular six-sided die. The face ‘number’ is the only input argument, k. Examples of the
desired output are shown in Figure 5.17. Notice the rounded corners. The orientation of faces 2,
3 and 6 does not matter as long as the white dots form the desired pattern.
start CHALLENGE
Dice Face
The challenge for this problem is to write the shortest possible code for the Dice function. The
length of the code is the number of characters ignoring the white spaces and new lines. (In real
competitions, the variable names of any length are counted as one character, and comments are
not counted at all. In our competition both of these will count.)
end CHALLENGE
Chapter 6
Some MATLAB commands for random number generation were mentioned before. Below is a list and
a short description of these commands:
rand Generates a random number with uniform distribution in the unit interval (interval
[0, 1]).
rand(n) Generates a square n × n matrix with random numbers in the unit interval.
rand(m,n) Generates an m × n matrix with random numbers in the unit interval.
randn Generates a random number from a standard normal distribution
(mean 0 and standard deviation 1).
randn(n) Generates a square matrix with random numbers from a standard normal
distribution.
randn(m,n) Generates an m × n matrix with random numbers from a standard normal
distribution.
randi(a) Generates a random integer from a uniform distribution between 1 and a.
randi(a,n) Generates a square matrix with random integers between 1 and a.
randi(a,m,n) Generates an m × n matrix with random integers between 1 and a.
randperm(a) Generates a random permutation of the integers from 1 to a.
randperm(a,k) Generates a random permutation of the integers from 1 to a and returns the first k
elements.
Figure 6.1 shows an example of the output of the three random generators (rand, randn and randi).
The list below details MATLAB commands for calculating some simple statistics. All operations
produce a single value if the argument a is a vector, and operate on each column separately, if a
is a matrix.
53
54 CHAPTER 6. DATA AND SIMPLE STATISTICS
1 4 20
0.8
2 15
0.6
0 10
0.4
−2 5
0.2
0 −4 0
0 0.2 0.4 0.6 0.8 1 −4 −2 0 2 4 0 5 10 15 20
Measures of Variability
std(a) Calculates the standard deviation of a.
var(a) Calculates the variance of a.
range(a) Calculates the range of a.
Data can be summarised and visually presented using bar charts, pie charts and glyph plots, among
many. Examples are shown in Figure 6.2.
Histograms summarise the data by splitting the range of the variable into bins, and then counting the
numbers of data points in each bin. An illustration is shown in Figure 6.3. The histogram is calculated
from a vector with 1000 value generated through the randn command using the following code:
a = randn(1000,1); figure, hist(a)
6.3 Examples
Generate 5000 random points in the unit square. Plot the data so that the points below the diagonal
joining points (0,0) and (1,1) are shown with blue crosses, and the ones above the diagonal, with red
triangles, as in Figure 6.4.
The first step after clearing the memory, the Command Window and closing the current figures, is to
open a new figure, and format the axes:
CHAPTER 6. DATA AND SIMPLE STATISTICS 55
>> bar(a) 10
>> a = [3 9 1 4 5];
8
>> pie(a,[0 0 1 0 0])
6
14%
23% 4
0
0 2 4 6
18%
41%
5%
>> glyphplot(a/max(a),'Standardize','off')
Figure 6.2: Examples of bar graph, pie chart and glyph plot
You can format the axes further by setting the font name and size. Compare the following two
continuations for this problem:
250
200
150
100
50
0
−4 −2 0 2 4
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0
0 0.2 0.4 0.6 0.8 1
end
end
2. Pre-generate the 5000 data points, and incorporate the condition into the plotting function.
Just for benchmarking the two versions against one another, regardless of the hardware, take the ratio:
1.603 seconds (first version) divided by 0.159 seconds (second version). The matrix calculation is over
10 times faster than the loop.
6.4 Exercises
1. Generate an array with 10 rows and 7 columns with random numbers between −1 and 5. The
numbers must not be integers.
2. Generate a vector column with 30 elements containing random numbers with a normal distribution
centred at 100 and with standard deviation 20.
(Hint: To offset the data, add the desired constant. To change the standard deviation, multiply
the data by the desired number. Think about the order of carrying out these operations.)
3. Plot the function y = sin(x 3 − 2) for 100 equally spaced values of x in the interval [0,2], using
solid black line. Draw a random sample of 10 values of x, and display the respective (x, y) points
CHAPTER 6. DATA AND SIMPLE STATISTICS 57
on the graph with marker red circle. Label the axes and add a title to the graph. The expected
output is shown in Figure 6.5.
(b) Generate an array A of size 20-by-20 of random integers in the interval [−40, 10].
Subsequently, replace by 0 all elements of A which are smaller than k.
(e) Visualise A using a random colour map containing exactly as many colours as there are
different elements of A.
(f) Extract 4 different random rows from A and save them in a new array B.
(h) Display in the Command Window the answers of (a), (c), (d) and (g) with a proper description
of each one.
5. Sub-plots
(a) Generate an array A with 200 random points in 2d, where both x and y vary from −100 to
100. Plot the points with black dots. As in sub-plot (a) in Figure 6.6.
(d) Plot in sub-plot (d) only those line segments from the previous question, whose length is
less than 50.
(a) (b)
100 100
0 0
y
y
−100 −100
−100 0 100 −100 0 100
x x
(c) (d)
100 100
0 0
y
−100 −100
−100 0 100 −100 0 100
x x
6. Suppose that you are testing a slot machine. The machine has 6 types of fruit. Appearance of
three of the same fruit guarantees a prize.
(a) Generate an array of 10,000 random outcomes of the three slots of the machine.
(b) Find the total number of winning combinations among the 10,000 outcomes.
(c) Assume that the entry fee for each run is 1 unit of some imaginary currency. Each winning
combination is awarded a prize of 10 units except for the combination of three 1s, which
is awarded a prize of 50. Assuming you are the owner of the slot machine, calculate your
profit after the 10,000 runs of the game.
7. Produce a game board similar to the one in Figure 6.7. The board should have 81 squares
arranged in a 9×9 matrix. Nine random squares should contain smaller red squares within, and
other nine random squares should contain a blue star symbol. The command ‘figure’ should be
included in your code.
start CHALLENGE
Two Lines
Use only 2 MATLAB lines (up to 75 characters including spaces) to produce the game board.
CHAPTER 6. DATA AND SIMPLE STATISTICS 59
end CHALLENGE
8. Try to reproduce Figure 6.8. The inside green disk has a radius of 0.7 units, and the white disk
has a radius of 1.5 units. Do not use loops.
−1
−2
−3
−4 −2 0 2 4
9. Create an imitation of a noisy signal as shown in Figure 6.9. Try to reproduce the figure. Do not
use loops.
10. Create an imitation of a noisy signal as shown in Figure 6.10. Try to reproduce the figure. Mark
the minimum and the maximum of the signal with yellow square markers.
60 CHAPTER 6. DATA AND SIMPLE STATISTICS
3000
2000
1000
signal
−1000
−2000
−3000
0 200 400 600 800 1000
time
800
600
400
amplitude
200
−200
−400
−600
0 200 400 600 800 1000
time
4000
3000
2000
1000
−1000
−2000
−3000
0 500 1000 1500 2000
11. Create an imitation of a noisy signal as shown in Figure 6.11. Try to reproduce the figure.
12. Craft one fill command to produce the grey shading as shown in Figure 6.12.
1
0 1 2 3 4 5 6 7
Next, generate two random vectors x and y. Each must have 1000 elements, so that the (x, y)
points are within the limits of the axes shown in the figure. Use one logical expression to
determine if a point is in the grey region. Plot only the points that are in the shaded regions on
your figure.
62 CHAPTER 6. DATA AND SIMPLE STATISTICS
13. Generate 10 points in the unit square and plot them with black dots. Generate another random
point and plot it with a red x. Your code should identify the closest black point and draw a red
circle around it. One possible output is shown in Figure 6.13.
0.8
0.6
0.4
0.2
0
0 0.2 0.4 0.6 0.8 1
14. Generate 2000 random values (not just integers) for x in the interval [−35, 165] and y in the
interval [−20, 80]. Figure 6.14 contains two ‘flowers’. One is a circle centred at (30,40), with
radius 30. The other is a circle centred at (−10, 0), with radius 40. Each flower (seen in red)
has green petals in the form of a circle at the same centre and radius 8. Reproduce the figure
depicting x and y with the respective colours. Do not use loops.
60
40
20
15. Carry out random search to find a minimum of the following function:
p
f (x1 , x2 ) = 2 sin 4x12 cos 6x23 − |x1 | (x2 − 5)
CHAPTER 6. DATA AND SIMPLE STATISTICS 63
using ranges: −4 < x1 < 4 and −4 < x2 < 4. Apply 1000 trials. Print the results in the MATLAB
Command Window. Plot in a figure the best value of the function versus the number of trials. An
example of the plot is shown in Figure 6.15.
3
Minimum F
2
−1
0 200 400 600 800 1000
Trial
(a) Using Monte Carlo simulations (a large number of random solutions), estimate what
proportion of the integer-valued 2 × 2 matrices are singular, where the matrix entries are in
the interval [−10, 10]. Format and display your answer in the MATLAB Command Window.
(Use at least 10000 random solutions.)
(b) Consider the integer-valued 2×2 matrices whose entries are in the interval [−k, k]. Calculate
the proportion of singular matrices of this type for k = 1, 2, . . . , 50. Plot the results on a
graph and give a short comment.
The following code is used by the teacher to generate the same dataset for an entire class.
You will need to run the snippet to obtain DataFile before clearing your workspace to continue
with this problem.
64 CHAPTER 6. DATA AND SIMPLE STATISTICS
(a) Import ‘DataFile’, containing the array Data, into your workspace. Each column corresponds
to a variable and each row is a data point described by the variables in the columns. Find
the means of all variables and display them in a bar chart. An example of the desired output
format is shown in Figure 6.16.
Figure 6.16: An example of the desired bar chart output for problem 6.4.17 (a)
(b) While most of the variables are random noise, there are relationships between two pairs of
variables (the ‘needles in the haystack’). Find a way to visualise all pairs of variables in
order to discover which pairs have the relationships plotted in Figure 6.17. Show the code
that you used for this visualisation. Plot the relationships you discovered as shown in the
figure. Put the true numbers of the variables instead of #X and #Y .
Figure 6.17: The relationship between two pairs of variables (the ‘two needles in the haystack’)
(a) Write MATLAB code to draw randomly a poker hand: 5 cards out of a standard deck of
52 cards (four suits: clubs ♣, diamonds ♦, hearts ♥ and spades ♠, and 13 values for each
suit: 2, 3, 4, ... 10, J, Q, K, A). Check whether the hand contains 3-of-a-kind. Keep sampling
until a hand with 3-of-a-kind is generated. Display the result the Command Window. For
example, the hand (10♦, 10♣, 2♦, K♠, 10♠) should be shown as 10D, 10C, 2D, KS,
10S.
CHAPTER 6. DATA AND SIMPLE STATISTICS 65
Also, print the number of hands sampled before reaching the 3-of-a-kind. Note; you should
guard against a ‘full house’ pattern where the remaining two cards are of the same value,
for example (10♦, 10♣, K♦, K♠, 10♠). This is not acceptable as a 3-of-a-kind hand.
Your code should draw a random poker hand, display it as in part (a), and display its value
in words. For example:-
10D, 10C, 2D, KS, 10S
three of a kind
Consider a hypothetical Welsh village with 10,000 inhabitants, of which 50% are male and 50%
are female. 20% of the male inhabitants are bald. 30% of female inhabitants are blond. 37% of
the inhabitants from the whole village population wear glasses. 10% of the inhabitants share the
surname Jones. 5% of the female population are called Carys, and 7% of the male population are
called Dafydd. (Bear in mind that the percentages are exact, not approximate figures.)
(a) Create a random matrix V that will hold the information about all the 10,000 inhabitants of
the village. Each row of V represents a person, and the columns represent the information
about that person from the description above.
(b) Take a random sample of 200 different villagers from V . Within that sample, find and display
in the Command Window (with precision 2 decimal places) the percentage of the following:
(a) Pick a random centre and radius of a circle in 2d. Pick also the coordinates of the bottom
left corner of a rectangle, as well as its width and height. All values should be randomly
drawn integers between 1 and 10.
66 CHAPTER 6. DATA AND SIMPLE STATISTICS
(c) Run Monte Carlo simulations to estimate the area of the intersection between the circle
and the rectangle. If the circle is contained entirely within the rectangle, or the rectangle
is contained entirely within the circle, the area should be calculated (not estimated).
Area = 8.5023
10
−5 0 5 10 15
Figure 6.18: An example of the output for the area estimation problem in problem 6.4.20
21. Government Agency X is planning to dispose of radioactive waste in the form of particles at
location (p, q). The pollution pattern follows a normal distribution centred at (p, q), with standard
deviation s km. The agency is concerned about a small village situated m km south and n km
west of the source of pollution. The zone of concern is a circle with radius k km around the
village.
(a) Give values to the parameters p, q, s, m, n, and k, and plot a figure to illustrate the pollution
pattern and the zone of concern.
(b) Create a function which will take the parameters as input, together with a number of
released particles. The output should be the number of particles in the zone of concern.
(c) Run Monte Carlo simulations to estimate the pollution rate in the zone of concern
(proportion). Note that you will have to call your function many times for this estimate
to be accurate.
(d) Evaluate the pollution as the number of particles per square kilometre (PPSK) if N thousand
particles were released by the source. Show a graph by varying N. Annotate the axes
properly. Show a progress bar during the calculation (waitbar).
CHAPTER 6. DATA AND SIMPLE STATISTICS 67
(e) The waste is expected to release one cloud of 15 thousand particles. Assume that the legal
pollution limit is 0.04 particles per square km. The agency has an option to move the waste
point north. Find (to the nearest kilometre) the southernmost possible position so that the
pollution in the zone of interest does not exceed the limit.
(f) Format and print in the Command Window a short report for Government Agency X,
containing your findings for the values given in (e). A few lines will suffice, for example
Currently chosen location of the waste point: (10,50).
Number of particles per square kilometre (PPSK): ...
Current PPSK safety limit: 0.04.
Suggested new location of the waste point: (...,...)
PPSK for the new location: ...
• The fitness function is the number of 1s in the chromosome – the larger, the better.
At each new generation, plot the best chromosome in the current population using the ‘spy’
command. Format the chromosome as a 25×25 matrix. An ideal chromosome will have all spaces
filled. The worst chromosome will be an empty square in the figure.
At the end, print out the fitness value of the best chromosome, and show the chromosome as
explained above.
Take the code from the previous problem and estimate the role of the mutation probability Pm . Run
it for values of Pm between 0.01 and 0.35 and plot a graph of the fitness of the best chromosome
against Pm . Give a short comment on the result.
Write a MATLAB script to simulate the behaviour of virtual bugs. The rules are:
• The bugs are initially randomly spread on a grid of 25×25 cells. Each grid cell receives a
bug with probability 0.4.
• At each step, a bug moves to a random neighbouring cell: up, down, left or right.
• If the move happens to be outside the edge of the grid, the bug disappears.
68 CHAPTER 6. DATA AND SIMPLE STATISTICS
• If more than one bug fall in the same cell, the cell destroys all of them.
Run consecutive steps until there are no bugs left on the grid. Display each iteration using the
‘spy’ command, and pause for 0.05 seconds to see the bugs moving. At the end of the run, print
the number of steps in the Matlab Command Window.
25. The travelling salesman problem (TSP) is defined in the following way. The salesman has to
visit n given cities. The order of visiting does not matter. The goal is to find an order of visiting
so that the distance travelled is minimum.
Write a function which implements a Monte Carlo simulation for the TSP. The function should
take as its input argument an array of (x, y) coordinates of the n cities, and should return a
permutation of the integers from 1 to n. The algorithm should check 50000 random solutions in
a loop. A graph should be plotted and updated along the run, every time a better solution is
found. An example of the end solution for n = 10 cities is shown in Figure 6.19. The title of the
figure should show the iteration number (loop counter) for the solution currently displayed, as
well as the tour distance. Run your function using n = 10 cities. The cities should be generated
at random in the unit square.
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0
0 0.2 0.4 0.6 0.8 1
26. Write a function for the TSP (see the previous question) using a ‘greedy’ approach. Starting with
the first city, identify the nearest city and add it to the list. Identify, among the non-visited cities,
the nearest one to the last city on the list. Keep growing the list until all cities are placed in it.
Close the tour to calculate the tour distance. Run your function using n = 10 cities. The cities
should be generated at random in the unit square.
27. Carry out a comparative study of the two approaches to the TSP problem using tour distance
and execution time as your two criteria. Choose a format to present your results.
Chapter 7
Strings
7.1 Encoding
In most programming languages, as with MATLAB, characters are actually represented by numbers.
There are numerous encoding schemes that are used in different scenarios and languages. MATLAB
(being primarily American) uses the ASCII - the American Standard Code for Information Interchange.
This scheme represents 256 possible character codes as numbers between 0 and 255, with each
character occupying one byte. Of these, 32 are so called ‘non-printable’ characters as they do not
produce any output on screen or when sent to a printer. There are 95 useful characters that can be
entered on a western QWERTY-style keyboard. Table 7.1 shows a selection of these 95 characters -
Latin numbers and letters only.
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
! " # $ % & ’ ( ) * + , – . /
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
0 1 2 3 4 5 6 7 8 9 : ; < = > ?
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
@ A B C D E F G H I J K L M N O
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
P Q R S T U V W X Y Z [ \ ] ∧ _
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
‘ a b c d e f g h i j k l m n o
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
p q r s t u v w x y z { | } ∼
69
70 CHAPTER 7. STRINGS
As characters are simply numbers, a matrix can contain a string. Each element will represent a single
character, and will be an integer between 0 and 255. Your other choice when dealing with multiple
strings would be to use a cell array (see Section 2.6).
7.3 Examples
planet(2:2:name_length) = cx(2:2:name_length);
else
planet(1:2:name_length) = cx(1:2:name_length);
planet(2:2:name_length) = vx(2:2:name_length);
end
planet(1) = upper(planet(1)); % capitalise the first letter
fprintf(’%s\n’,planet);
end
There is a customer at the till. They want to purchase 3 random products with specific quantities for
each. To prepare your receipt:
1. Select randomly 3 products from your list. For each product choose a random quantity between
1 and 9.
4. Suppose that the price includes 20% VAT. Calculate the amount of VAT included in the price.
5. Prepare the receipt as text in the MATLAB Command Window. Use the current date and time
(check the command datestr(now,0)).
Your code should output the receipt in the format shown in Figure 7.1. There should be 60 symbols
across. Choose your own shop name.
Solution.
% Entries
rp = randperm(6); % first 3 products were purchased
Quantity = ceil(rand(1,3)*9); % how many of which
ItemPrices = Quantity .* prices(rp(1:3));
% Frame
Rec = repmat(’ ’,16,60); % empty template
[Rec(1,:),Rec(end,:)] = deal(’-’); % side frame
72 CHAPTER 7. STRINGS
% Fill in
Rec(3,3:length(datestr(now,0))+2) = datestr(now,0); % today’s date
shop_name = ’Grandma’’s Little Shop’;
Rec(3,end-length(shop_name)-1:end-2) = shop_name;
for i = 1:3
S = sprintf(’%25s (%1i) x %5.2f = £ %6.2f’,products{rp(i)},...
Quantity(i),prices(rp(i)),ItemPrices(i));
Rec(i+5,3:length(S)+2) = S;
end
Rec(9,29:54) = ’-’; % line under the list
Rec(10,16:27) = ’Total to pay’;
Rec(10,43:52) = sprintf(’ £ %6.2f’,sum(ItemPrices)); % total price
Rec(11,25:27) = ’VAT’;
Rec(11,43:52) = sprintf(’ £ %6.2f’,sum(ItemPrices)/6); % VAT
bye = sprintf(’Thank you! You have been served by %s’,...
staff{ceil(rand*4)});
Rec(14,3:length(bye)+2) = bye;
disp(Rec)
7.4 Exercises
1. Coded Messages
(a) Create a random coded message as a 10-by-50 matrix with integers corresponding to ASCII
codes. See Table 7.1 for the required codes. Using the command char, display the message.
CHAPTER 7. STRINGS 73
(b) Find the number of occurrences of capital letters. Replace all such occurrences with
the symbol # (The ASCII code for # is 35. To find the ASCII code for a character, type
double(<the_character>).
(c) Turn your original message into a table with k columns, as shown below for k = 5. Notice
that the table has the same size as the original message (10-by-50). The top and bottom
rows are replaced with dashes, and the respective columns are replaced by vertical bars.
(You should be able to change the value of k in the code and display a table with the
desired number of columns.)
+---------+---------+--------+---------+---------+
|YJDxLsTbY|kyTXDLBuq|zRCEASUM|QEYZAFlGo|hDFhuccfE|
|zBkRfAVvM|qBhgYtPGr|jGvvsPHC|PzpSfMgdn|XOIYmDKdN|
|eGWdsvmKM|ixVwBSajA|udWKvIwH|XUqUMwizt|zaqUEBoIB|
|qOjwjmtJO|LJZWDalLi|EIbJtsFJ|fKtwFueRI|dfaLbblDK|
|ZJqIPOsnh|xLzryivOD|PYewnPoO|QAqbHsJto|vqvrudsTm|
|ZlZToSxDm|RcmFJGsey|AgaWoZFB|qAVKxlRUZ|trOjsrZib|
|zGsWgtavw|TeqyJhyQE|yQReYONR|KWJgiKwKI|WCTNIhKUo|
|xqxqmopTB|ZhUUSlovO|ACxarMmR|bZonYojEx|zCJxRmXAq|
+---------+---------+--------+---------+---------+
2. Extract the first e-mail address from a string. Check whether the e-mail is from the UK (ending
with ‘.uk’) and display the extracted address in the Command Window, indicating ‘UK’ or ‘NON-
UK’. Demonstrate the work of your code on strings of your choice.
3. Construct arrays containing (i) quantifiers (e.g., all, few, many, several, some, every, each, any,
no, etc.), (ii) nouns or expressions (animated), (iii) verbs and (iv) another array with nouns or
expressions. Draw randomly one word from each array to construct a funny random proverb. A
few examples:
displayed in the Command Window. It then progresses taking a sentence from the user and
displaying the last word in a question:
For example, if the user inputs ‘It is snowing today.’ your program should print ‘Really, today?’
5. Write MATLAB code which will do the following. Ask the user to input a short sentence. Replace
the spaces with a dash and display the text as shown in the example below.
Suppose that the text is ‘Joey is a super cat!’ Your output should be:
!
t! ...
at! a-super-cat!
cat! -a-super-cat!
-cat! s-a-super-cat!
r-cat! is-a-super-cat!
er-cat! -is-a-super-cat!
per-cat! y-is-a-super-cat!
uper-cat! ey-is-a-super-cat!
super-cat! oey-is-a-super-cat!
-super-cat! Joey-is-a-super-cat!
6. Manipulating Strings
Once upon a time, a very long time ago now, about last Friday, Winnie-the-Pooh
lived in a forest all by himself under the name of Sanders. “What does ’under the
name’ mean?” asked Christopher Robin. “It means he had the name over the door
in gold letters, and lived under it.”
Make sure that your code does not exceed the width of the MATLAB editor’s page (75
characters).
(b) Use the names of three celebrities of your choice to replace in the string the three names:
Winnie-the-Pooh, Sanders and Christopher Robin.
(c) Find the number of characters, with and without counting the spaces. Display your answer
in the following format in the Command Window:
(d) Find the total number of words in the string (repeated or not). Assume that any two words
are separated by a space. Display your answer in the Command Window.
7. Count the number of words in a string, excluding ‘the’, ‘a’ and ‘and’, regardless of capitalisation.
Demonstrate the working of your code with an example string.
8. Create an Anagram game using MATLAB. You will need to create a cell array with the names of
the countries in Europe shown in Table 7.3. Next, randomly choose a country, mix-up the letters
to make an anagram, display it in capital letters, and ask the user to recognise the country. The
CHAPTER 7. STRINGS 75
user is allowed 3 attempts. If the user inputs the correct name (at any of the three attempts),
display a message of congratulation and stop. If all three attempts are unsuccessful, display an
appropriate message and stop.
9. Write MATLAB code to print, in the Command Window, a decorated Christmas tree as shown
below. The candles (i) and the balls (O) should be at random places. Notice the star (*) at the
top and the stump (I) at the bottom of the tree. Aim to write the shortest possible code.
*
^iO
i^^^^
^^^i^^O
^^^^^^^O^
^^^^^^^^^i^
^^O^^^^^^^^^i
^^^O^^^^^^^^^^^
^^^^O^^^i^^^^^iiO
I
10. Write a function which will take a matrix A as its input argument, and will print in the Command
Window a LATEX script for this matrix. In LATEX syntax. The columns should be right-aligned and
the matrix should be given in large square brackets. For example, the matrix
A =
7 9 -4 10
9 3 1 -6
-7 -8 10 10
76 CHAPTER 7. STRINGS
should be coded in LATEX as the script below. When placed in the equation environment (opened
with ‘\[’ and ended with ‘\]’), the matrix should look like the one shown to the right.
\left[
\begin{array}{rrrr}
7&9&-4&10\\ 7 9 −4 10
9&3&1&-6\\
9 3 1 −6
-7&-8&10&10\\ −7 −8 10 10
\end{array}
\right]
Write a function which takes a text string and a template as input, and places the words in the
shape of the template. The template should be a binary matrix with ones where the ascii symbols
should be. The function should return a string. An example is shown below:
If i t w
asn’t fo r t
he coffee, I’d
have no identifia
ble personality what
sover.If it wasn’t for t
he coffee, I’d have no ident
ifiable personality whatsover.If
it wasn’t for the coffee, I
’d hav e no identifiabl
e pers onality whatsove
r.If i t wasn’t for the
coffe e, I’d have no i
dentifiable pers onal
ity whatsover.If it
wasn’t for the c offe
e, I’d have no i dent
ifiable personal ity
whatsover.If it wasn’t for t
he coffee, I’d have no identifiable personality
whatsover.If it wasn’t for the coffee, I’d hav
Ch
rist
mas fo
rever!Ch
ristmas fo
rever!Christ
mas forever!Ch
ristmas forever!
Christmas forever!
Christmas forever!Ch
ristmas forever!Christ
mas forever!Christmas fo
rever!Christmas forever!Ch
ristmas forever!Christmas fo
rever!Christmas forever!Christ
mas forever!Christmas forever!Ch
ristmas forever!Christmas forever!
Chapter 8
Images
8.1 Types of Image Representations
MATLAB supports the image representations detailed in the following sections. The core version has a
limited set of image commands. To check whether you have a license for the Image Processing Toolbox,
type in the Command Window:
license(’test’,’image_toolbox’).
78
CHAPTER 8. IMAGES 79
the combination of the red intensity A(i, j, 1), green intensity A(i, j, 2) and blue intensity A(i, j, 3). Each
value is stored in 8 bits, as unsigned integer, format uint8. Value (0,0,0) for (A(i, j, 1), A(i, j, 2), A(i, j, 3))
makes pixel (i, j) black, and value (255,255,255), makes it white. Equal values in the three planes will
make the pixel grey, with intensity determined by that value. An example of an RGB image and its
MATLAB representation are shown in Figure 8.2.
Image
1 2 ... 1136 Columns of pixels
1
2
Dark green
852
Rows 16
of pixels Blue plane
55
Green plane
Light grey 33
Red plane
(215, 210, 191)
A grey intensity image is represented as a matrix A of size M × N. Again, M is the number of rows of
pixels and N is the number of columns of pixels. Using the uint8 format, A(i, j) takes integer values
between 0 (black) and 255 (white), specifying the grey level intensity of the pixel in row i and column
j. Each of the three planes of an RGB image is an intensity image itself.
1
Image 2 MATLAB code
.
.
. a = repmat(0:255,700,1);
b = fliplr(a);
figure('color','w')
imshow(uint8([a b(:,1:80)]))
700
5 colours
Colour map
3 3 3 1 4 4 4 0 4 4 2 2 4
3 3 2 4 0 0 0 0 0 0 0 2 0
1 2 4 0 0 2 2 2 2 2 0 0 2
0 0.07 0.08 0.18
2 4 2 0 0 2 1 1 1 1 0 0 2 1 0.70 0.71 0.86
3 3 3 0 0 2 2 1 1 2 2 0 0
3 3 3 1 0 0 1 2 2 2 0 0 2 2 0.36 0.38 0.64
3 3 3 3 0 0 0 1 2 0 0 2 3
3 3 3 3 3 0 0 0 0 0 1 3 3 3 0.99 0.99 0.99
3 3 3 3 3 3 3 1 1 3 3 3 3
3 3 3 3 3 3 3 3 3 3 3 3 3 4 0.06 0.07 0.55
3 3 3 3 3 3 3 3 3 3 3 3 3
3 3 3 3 3 3 3 3 3 3 3 3 3
This command will concatenate the three planes on the third dimension.
Sometimes it is necessary to store the coordinates of the pixels in an image. Consider the following
command
[x,y] = meshgrid(1:5,1:3);
x =
1 2 3 4 5
1 2 3 4 5
CHAPTER 8. IMAGES 81
1 2 3 4 5
y =
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
Notice that the y coordinate starts from top and increases with the row index. This is the ij-coordinate
system available in MATLAB. To plot in a figure, with this system, set the axes by axis ij.
Table 8.1 contains useful commands and functions for handling images in MATLAB.
8.3 Examples
One potential approach for solving this problem is shown in Figure 8.6. The code is shown below.
Figure 8.6: A possible approach for the solution of the half-grey-image problem.
for i = 1:s(1)
for j = 1:s(2)
if (j-1)/(s(2)-1) - (i-s(1))/(1-s(1)) < 0; % top half
A(i,j,:) = B(i,j);
end
end
end
figure,imshow(A)
While this approach works; it is slow, and not in the spirit of the language. Instead of the double loop,
we can create a mask which will have values TRUE for the top diagonal half. Then we will replace
the top diagonal halves of the RGB planes of A with the the corresponding values in B, and finally
re-assemble A. The code for this version is shown below.
To create an ASCII version of a grey image, rescale it to a desired resolution, and convert it to index
image using gray2ind command. The number of shades in the colour map should be the same as
the number of symbols used to represent grey values. For example, you may wish to use the following
set of characters:
S = ’#n*:. ’;
An example using this character set is shown in Figure 8.7. To achieve a good result, the background of
the original image should be removed. The colours should be preferably in patches. Good candidates
for ASCII art are cartoon images.
.......
...:::.:::..::...
.::::::::::*:****:::
.:******::**nn**nnn*:..
.****nn:*nn*::nnnn**:::::..
:***nnn*:n##n:.:nnn**n*****:.
.***nn*n*****:::*nn*nnnnnn**n*.
:*******nnnnnnnnnnn*nn##nn#nnn:
.*******nnnnnnnnnnnnnnnnn##n*.n:
.:***n*nnnnnnnnnn***nnn*:***..*.
.::**nnnnnnnnn*******nnnn: ..
:::****nnnnn*********nnn*.
.:::::********************
..::::::******************:
....::::::::::***********::::
.......::::::************:::::::
.............::::::****:::::::::::::.
.......::.....::::::::::::::::::::::::::.
.......::.........:::::::::::::::::::::::::..
......::...........:.:::*:::::::::::::******:::..
.........................::**:::::::**********:***:.
...::.........................::****:****::*****::*n***:
..::::::**..........................:*************::::*nnn**.
.:**nnnn*******:................:::::::::.:*****************nnnn*:
.n#nnn********::..........:.:.:::::::::::*n****************nnnn:
..:*nnnnnnnn*::****:::::::::::::.::::::::::*nn****************nnn*:
...::::*nn#nnnnnnnn*::**nnn*::::::::::::::::::::**nnn*****************:.
..:::***********nnnnnnnnnnn*::nnnnnn***:::::::**::**n**nnn*******************.
.:*nnnnnnnnnnnnnnnnnnnnn*****nnnnnn*nn**nnn*::********nnnnnnnnnnn***********nnnn**:
..:**nnnn*****:::.... ...:****nnnnnnnnn##n###n*nnnnnnnnnnn**nnnn**nnnnn**::.
..:nn##n#n#####nnnnnnnnnnnnnnnnnnnn*******nnn**::. .
.:*n#nn#nnnnnnnnnnnnnnn#nnnn*:.. .... .:**n*: .:::.
.:*nnnnnnnnnnn##nn**:.. .::::::::..::**.
.:nnnnnnnn:.. ..:**:::**:...
.*nnnnnn. ..:.
:nnnnn#n:.
.:****n#n*:......
..::..::::*#####nnnnnnn*::::..
:nnnn#nnnnn**::::........
...
Notice the particularly elegant way to construct the ASCII output, S(C+1). The set of characters S
is indexed with the index image values. These values are meant to be entries in the colour map, also
sorted from dark to light. The output is shaped as the index C .
The indexed image, however, starts the counting from 0, while the array with the characters S must
be addressed, according to the MATLAB rules, from 1. Therefore we add 1 to C when using it as
index.
8.4 Exercises
1. Ask the user for a number between 1 and 4. Depending on the entered number, create and
display a matrix of a random colour, where the respective quadrant has a different random
colour. Examples of the four outputs are shown in Figure 8.8. Use the switch-case operator.
2. Reproduce Figure 8.9 by creating manually an indexed image and setting the respective colour
map.
3. Generate a matrix and colour it so that it resembles the tartan pattern in Figure 8.10 or another
similar pattern.
4. Load a JPEG image and plot the histograms of the red, green and blue panes of the image as
shown in Figure 8.11. Note; the histograms should appear on one figure.
CHAPTER 8. IMAGES 85
5 Red
x 10
5
0
0 50 100 150 200 250
5 Green
x 10
5
0
0 50 100 150 200 250
5 Blue
x 10
5
0
0 50 100 150 200 250
(a) (b)
Figure 8.11: The original image (a), and the histograms of the three panes (b)
5. Load a JPEG image and convert it to an indexed image with 5 colours. Create a random colour
map for the new image. Show the original and the new image. An example is shown in Figure 8.12.
6. Load a JPEG image and reduce its intensity to make it into a watermark image as demonstrated
in Figure 8.13. Do not use the ‘brighten’ command; manipulate the image with your own code.
7. Load a JPEG image of your choice. Convert it to grey and calculate the mean and the standard
deviation of the grey level intensity. Display a new image where all pixels within one standard
deviation from the mean are coloured in red, and the remaining pixels stay unchanged.
8. Write a function that will take an RGB image and a character, which can be only R, G or B,
as input arguments. The output of the function should be an RGB image of the same size as
the input image, where the indicated panel (red, green or blue) is replaced by a random matrix.
Demonstrate the work of your function by writing a script, calling the function with each of the
86 CHAPTER 8. IMAGES
Figure 8.12: The original image and the indexed image with 5 random colours
three character values. Organise the output into a 3-by-1 montage and show it in a new figure.
An example is shown in Figure 8.15.
CHAPTER 8. IMAGES 87
Figure 8.15: A montage with random red, green and blue panels
9. Write a function that will load an image chosen by the user and create an ‘old movie’ effect:
tinted, faded, scratched and torn at the bottom. An example of the original image and the desired
effect is shown in Figure 8.16.
10. Take a grey image and inset 6 progressively smaller versions of it into the top left corner, as
shown in Figure 8.17. Each subsequent image should be half of the size of the previous image
in both dimensions.
11. Construct and display the image in the left plot of Figure 8.18, containing red, green and blue
panels where the colour appears gradually from left to right, starting with black.
Next, add three more panels combining the RGB colours as in the right plot of Figure 8.18. The
colours in the bottom row should be approximately brown, purple and tobacco.
12. Take a JPEG image and tint the four quadrants with transparent overlays as shown in Figure 8.19.
(a) Create a function which frames an image. The input arguments are the image, a proportion
p that defines the frame size, and the frame colour. The frame colour should be given as
a vector of three numbers between 0 and 1. The proportion for the frame width should be
88 CHAPTER 8. IMAGES
Figure 8.17: A grey image with progressively smaller copies inset within
taken from the smaller of the two dimensions of the image. The frame should be inside the
image. Examples of framed images are shown in Figure 8.20. Demonstrate the output of
your function in a similar way with three different sets of parameters.
CHAPTER 8. IMAGES 89
(b) Use your function in a loop to create a montage as shown in Figure 8.21. The frame width
and the frame colour should be random. The frame width should be no larger than 30%.
14. Load a JPEG image and draw a grid with 10 rows and 10 columns of cells on it, as shown in
Figure 8.22. The grid lines should be embedded in the image, and not merely plotted on the
same axes. The width of the lines should be chosen in such a way that the lines are visible.
Also, make your code re-usable so that it can work on any image you upload. (This means that
there should be no hard coded constants in your function/script.)
15. Play a game with your friends. Encrypt a colour image of size [M, N, 3] using a random
permutation of the integers from 1 to M × N × 3. Save the encrypted image in a mat file,
together with M, N and the permutation used. Challenge your friends to decrypt the image from
the mat file. You can run a contest to find the first person to show the correct original image.
16. Construct the function shuffle_image that will take an RGB image and two integers, M and
N. The function should split the image into M rows and N columns of ‘tiles’. It should return an
90 CHAPTER 8. IMAGES
image of the size of the original input but with shuffled tiles. An example of the original image
and the shuffled image, for M = 4 and N = 5 is shown in Figure 8.23.
Note: If needed, make the image sizes multiples of M and N, respectively, by losing a small
number of bottom rows and right-hand side columns of pixels.
Figure 8.23: The original image and the 4×5 shuffled image.
17. Create a function named image_blocks. The input arguments are: x, an RGB image; N,
number of rows of blocks; M, number of columns of blocks; and p, a parameter to chose between
mean/median/mode.
The output should be an RGB image y of the same size as x, split into N rows and M columns of
blocks of colour. The colour of each block should be the mean/median/mode colour of the pixels
within this block in the original image. The value of p will determine which one of the three
CHAPTER 8. IMAGES 91
options is used. Examples of an original image and the outputs for the three options are shown
in Figure 8.24.
18. Create a MATLAB function which takes as input a cell array with words (strings) and an integer
mode. The length of the array is not limited. The function should display the words around a
shape as shown in Figure 8.25. If the switch mode is 1, the words should be sorted alphabetically
before displaying. Finally, load and display an image, create axes within it, and call the function
to display the entries in the cell array as in the Figure. (Hints: (i) You may need to darken the
image for the text to be clearly visible. (ii) The function output should have the handles to the
lines so that their visibility can be turned off.)
Monday
bear
lf
wo
cat
er
ay w
y
da tig
n esd co
Tu
Su
squirrel
dog
shee
elep
Saturd
ay Wedn p
esday han
t
m
fo
ou
x
Frid
monk
goat
Thu
se
ay
rsd
ey
ay
Figure 8.25: Examples of the output for the circular text problem.
(a) Load a JPEG image (for best effect, this should be a low resolution, nearly square cartoon
image). Choose the number of rows, M, and the number of columns, N, for the painting grid.
Resize the image to the required grid size.
(b) Convert the JPEG image into an indexed image with 8 colours and show it as in
Figure 8.26 (b).
(c) Prepare a figure that displays the colour map as shown in Figure 8.26 (c).
(d) Prepare a figure that shows the grid and the numbers of the colours as in Figure 8.27.
92 CHAPTER 8. IMAGES
start CHALLENGE
Write the script for problems (a)-(d) using the minimum possible number of lines. The rules are:
(1) Each line has a maximum of 75 symbols. (2) The number of characters does not matter. (3)
The figures may be produced in any order but each figure must be opened with the figure
command. (The authors’ current record is 7 lines.) Best of luck!
end CHALLENGE
20. 3D Colours
Each pixel in an image can be regarded as a point in a 3-dimensional space: RGB. Thus the pixels
can be plotted using command plot3 or scatter3. In addition, each pixel can be plotted with
its own colour. Examples of three images and the respective 3D plots are shown in Figure 8.28.
Create a similar colour cube for an image of your choice. If you are plotting in a loop using
plot3, make sure that you rescale the image to a much smaller size so that the number of
plotted points does not exceed, say, 50,000. Otherwise the plotting will be too slow.
CHAPTER 8. IMAGES 93
250
250
200
150 150
150
100
100
100
400
50
50 50
300 200
0 0
0 200 0
100 100 0 200
200 0 50 100 400 0 50 100 150
0
300 0 150 200 250 200 250
Animation
9.1 Animation Methods
There are several ways to produce animation in a figure in MATLAB. The figure can be redrawn with
the new positions of the objects being animated. Another (and more elegant) way is to keep the figure
and change only the positions of the objects. To do this, we need to take handles of the objects of
interest. These handles contain information about all properties of the respective objects, including
position and colour. An example of creating a handle is shown below;
h = plot(0,0,’k.’);
Among the many properties displayed in the Command Window, there are:
Color: [0 0 0]
LineStyle: ’none’
LineWidth: 0.5000
Marker: ’.’
MarkerSize: 6
MarkerEdgeColor: ’auto’
MarkerFaceColor: ’none’
XData: 0
YData: 0
The coordinates of the marker are in properties XData and YData. Each property can be modified
using the set command. For example;
set(h,’Marker’,’d’,’Markersize’,40,’Linewidth’,3)
will replace the dot marker in the figure with a diamond marker of size 40, drawn with a thick black
line. Note that any number of properties can be changed with one set command. MATLAB is not
case sensitive with respect to the properties’ names, so XData is the same as xdata. (In some cases
the properties can even be abbreviated; however until you are more familiar with them use, the full
property name.)
95
96 CHAPTER 9. ANIMATION
To make the animation work, the changes must be displayed with a short time delay. Use the
command
pause(s)
where s is a number of seconds. You will usually use a fraction of a second between two consecutive
appearances of the animated objects.
When an object is drawn using a sequence of x, y coordinates, the set function will assign all the new
values together. For example, if the object h is a triangle, both the XData and the YData will contain
three values. Then
set(h,’XData’,[3,2,9],’YData’,[12,4,3])
will assign the new coordinates to the respective vertices of the triangle.
This function returns 0 when terminated by a mouse click, or 1 when a key is pressed.
Mouse clicks can be used to grab an object. For example, upon a mouse click, the variable gco contains
the handle of the object on which the click fell. If the click was not on any drawn object, gco will
return the handle to the figure. For example, try the code below. It will draw a triangle and change
its colour every time you click on the object. The loop will stop when a key is pressed.
h = fill(rand(1,3),rand(1,3),rand(1,3));
axis off
while ~waitforbuttonpress
if gco == h
set(h,’FaceColor’,rand(1,3))
end
end
The coordinates of the last mouse click can be read into a variable using;
point = get(gca,’CurrentPoint’);
In two dimensions, the x coordinate is in point(1,1), and the y coordinate is in point(1,2). Figure 9.1
shows an example of a line drawing using mouse clicks.
CHAPTER 9. ANIMATION 97
0.8
mouse position
(in axes 0.6
coordinates) 0.4
0.2
0
0 0.2 0.4 0.6 0.8 1
start CHALLENGE
Without running the code below through MATLAB, try to figure out what it will do within 2 minutes.
Draw on a piece of paper your predicted output. Subsequently, run the code and check whether you
were correct.
figure(’color’,’k’)
axes(’Position’,[0 0 1 1]), hold on
axis([-1 2 -1 2],’off’)
for i = 1:15
pl = ginput(1);
fill(pl(1)+rand(1,3)-0.5,pl(2)+rand(1,3)-0.5,...
rand(1,3),’EdgeColor’,’w’)
end
end CHALLENGE
9.3 Examples
the handle
figure
h = plot(0,0,'k.','markersize',200);
axis([-1 1 -1 1])
axis square off
figure,hold on
h1 = plot(0,0,’r.’,’markersize’,100); % red marker
h2 = plot(0,0,’b.’,’markersize’,100); % blue marker
h3 = plot(0,0,’g.’,’markersize’,100); % green marker
plot([0 100 100 0 0],[0 0 100 100 0],’k-’) % outline the square
axis([-3 103 -3 103]) % set the axes
CHAPTER 9. ANIMATION 99
% Fancy Stopwatch
bzz_freq = 1600; % needed for the short beep sound
fs = 8000; % the sampling frequency
1
A full circle contains 2π radians.
100 CHAPTER 9. ANIMATION
figure
axis([-1.1 1.1 -1.1 1.1],’square’,’off’) % format the axes
hold on
9.4 Exercises
1. Fireworks. Use the mouse to create figures similar to the ones in Figure 9.5. On a mouse click,
the centre of the star should be plotted at the position of the mouse. 100 random rays should
be drawn from the centre. The next mouse click will generate a new star centred at the mouse
position. The colours of the stars are random. The script should finish when a key, on the
keyboard (rather than on the mouse), is pressed.
2. Highlighting
CHAPTER 9. ANIMATION 101
Load and show an image of your choice. When the user clicks on the image, highlight the region
around the position of the click. The size of the region should be a changeable constant in your
code. An example is shown in Figure 9.6.
4. Create an animation so that 10 squares, nested as in Figure 9.7, evolve simultaneously. The
outer square disappears at the next step, and all 9 inside squares grow by one size. At each
step, a new smallest square of a random colour appears in the middle. Each square must keep
its colour during the growing stages. An example of 4 consecutive steps is shown in Figure 9.7.
5. The dashed lines in Figure 9.8 show two trajectories: sin(θ) and cos(θ), where θ varies from
0 to 4π. Create an animation where a black square marker and a red triangle marker move
simultaneously in 400 steps, following the respective trajectories.
1
1
0.8 0.8
0.6 0.6
0.4 0.4
0.2 0.2
0 0
−0.2 −0.2
−0.4 −0.4
−0.6 −0.6
−0.8 −0.8
−1 −1
0 50 100 150 200 250 300 350 400 0 50 100 150 200 250 300 350 400
Figure 9.8: Animated triangle and square markers moving along a sine and a cosine trajectories
6. Open a figure with a yellow background. Place a text string ‘Stopwatch’ near the top left corner.
Use large letters, and a font of your choice (not the default font). Position anywhere in the figure
the number zero, with a larger size of the chosen font. Ask the user to input a number of seconds.
Get your stop watch to count the seconds in nearly real time. An example of the clock face is
shown in Figure 9.9.
Take into account that there is a slight delay due to the printout, so the ‘pause’ command should
not be exactly for 1 second but a little less. (Hint: Use tic and toc to time 10 seconds and
tune the argument of the ‘pause’ function accordingly.)
Stopwatch
16
Figure 9.9: An example of the stopwatch face
7. Plot a circle trajectory as shown in Figure 9.10 (a). Plot a large black round marker on the zenith
of circle. Shade the bottom half of the figure grey. Make the marker complete a full circle on the
drawn trajectory in 100 steps. Change the dot into a diamond when it enters the shaded zone,
CHAPTER 9. ANIMATION 103
and revert it back to dot marker when it leaves the zone. In addition, make the diamond change
its fill colour randomly at each step. An example is shown in Figure 9.10 (b).
8. Planets
(a) Create an animation of a solar system with one sun and two planets. Each planet orbits
the sun in a circular orbit. The two orbits have different radii. One of the planets goes
clockwise, and the other goes anti-clockwise. The outer planet takes twice longer to make
one full circle than the inner planet. Plot in the animated figure the two orbits with dashed
lines. Remove the axes and make sure that they stay square and fixed (don’t float with the
animation).
(b) Give the outer planet a moon. Plot the just the orbit of this moon (a circle around the planet)
and make sure that the moon and its orbit move together with the planet. The moon itself
does not have to follow its orbit for now.
(c) Make the moon orbit its planet at a speed that you choose.
An example of the required figure is shown in Figure 9.11. The text is NOT required. It is for
your reference only
Sun
Inner planet
9. Fish Tank
Use MATLAB to draw a fish tank as shown in Figure 9.12. Place a fish near the left wall. You
can draw the fish using markers and filled polygons. Make the fish move slowly across to the
right wall of the tank. When the fish reaches the middle; it should breathe out three bubbles
which float towards the surface. Figure 9.12 (a)–(d) show the beginning, middle and end of the
animation.
(a) Create a function which that has two input arguments; a number of sectors N, and a colour
v (a vector of red/green/blue, each component in the interval [0,1]). Open up a figure and
plot consecutively N sectors (triangles) in a circle. Starting with a white sector, animate
each subsequent sector appearing. The sector should have an interpolated colour between
white and v. An example of the output is shown in Figure 9.13 (a). Make sure that the figure
size does not change with each new sector that appears. Write a script to demonstrate the
function and give examples of the output.
(b) Expand the function written in (a) to include a third boolean (true/false) input parameter. If
true, the starting colour is white; if false, the starting colour is black. An example with a
black start sector is shown in Figure 9.13 (c).
(c) Write MATLAB code which calls your function, and then waits for a mouse click. If the click
is on a sector, the colour of this sector changes to the opposing colour. For example, if the
current colour is [0.3 0.7 0.2], the opposing colour is [1, 1, 1] − [0.3, 0.7, 0.2] = [0.7, 0.3, 0.8].
If the click does not fall on any sector, close the figure. An example with several clicks is
shown in Figure 9.13 (d).
(a) Write a MATLAB function that will take three input arguments: k, the number of vertices
for a shape component, r ∈ [0, 1], a scaling factor, and m the axis limit (for formatting the
axes using axis([-m m -m m]). The function must open up a figure, plot a symmetrical
shape of a random colour, scale it by r, and rotate it about the middle to a full circle using
CHAPTER 9. ANIMATION 105
(a) During Animation (b) End State (c) Black Start Sector (d) Opposing Colours
100 steps. An example of the type of the required shape is shown in Figure 5.11 (see the
problem about producing this shape).
(b) Write a script that calls the function from the previous problem 10 times, with the same
scaling factor and axes limit. After the calls, the current figure should have all 10 forms
in it as shown in Figure 9.14 (a). On a new figure, make 10 calls to the function with a
progressively decreasing scaling factor. An example of the figure at the end of the 10 calls
is shown in Figure 9.14 (b).
Create an animation starting with three squares as shown in Figure 9.15 (a). The black square
rotates clockwise and completes a full circle around the centre. Figure 9.15 (b) shows a position
of the square during the animation.
Write MATLAB code to produce the following animation. Plot two triangles as shown in
Figure 9.16 (a). Each of the two triangles should rotate in a full circle about the centre. The two
rotations should be in different directions as shown in Figure 9.16 (b) to (d). The final position
should be the same as the starting position. The rotation should be done in 100 steps. At each
106 CHAPTER 9. ANIMATION
step, each triangle should assume a new random colour. The tips of both triangles should produce
a dot trace as shown in Figure 9.16 (b) to (d).
14. Write a script that will run 15 random jumps of a ‘frog’ within a ‘pond’. The pond should be the
unit square coloured in blue. The frog must pause for 0.5 seconds at each location. It should and
leave a trajectory behind, plotted with a dashed green line. The initial position of the frog is the
point (0.5,0.5). The frog should be presented as a green triangle. The expected output at the end
of the animation is shown in Figure 9.17.
Plot a collection of 9 folders of random pastel colours. Offset them as shown in Figure 9.18. (Hint:
use function rectangle which allows for round corners.) Label the folders with the numbers
from 1 to 9 as shown in the figure. After a key is pressed, make the folders shrink and disappear,
one at a time, in a random order. The folder number should disappear before the shrinking starts.
Recall the problem, from the Images Chapter, where you had to create a function that breaks up
an image into blocks, and shuffles the blocks? Use your solution to help with this problem.
CHAPTER 9. ANIMATION 107
Figure 9.17: Expected output at the end of the animation for the jumping frog problem
Load an image, called the ‘Original’ (you don’t need to use a picture of eggs!). Split the image
into 4-by-5 tiles and shuffle them, the ‘Scrambled eggs’ - as shown in Figure 9.19.
Here comes the twist: manipulate the scrambled image further, so that one random tile is missing,
and another random tile is repeated in its place. Display the image as in Figure 9.19 ‘Repeated
tile’. Hold for 3 seconds, and then display another figure where the whole image is darker apart
from the two repeated tiles, which should stay of the same colour.
Challenge your friends to discover the repeated tile within the three second interval.
108 CHAPTER 9. ANIMATION
17. Load a JPEG image and make the four quadrants blink with different transparent colour: red,
green or blue only, in a clockwise pattern. An example of a full rotation of four random colours is
shown in Figure 9.20. (Hint: The transparent colour is obtained by setting the respective colour
pane to the maximum value while keeping the other colour panes.)
Create a 10 by 10 matrix filled with ones which will be the grazing ground. Plot the ground
using the spy command, as shown in Figure 9.21. Create a ‘grazer’ at a random position in the
array.
10
15
20
25
0 5 10 15 20 25
nz = 571
The grazer moves to a randomly chosen neighbouring cell at each time step. Neighbouring cells
are only north, south, east and west (i.e. four-connected cells). The grazer is not allowed to move
out of the borders of the grazing ground. It eats the provision in the cell it is in, which is marked
as empty space in the Figure. The grazer itself is a red square marker.
Your animation should show the grazing ground and the grazer’s position at each step. The code
is run until there is no food left.
You can run a competition with your friends for the fastest grazer.
19. Load a JPEG image and, after a key is pressed, make a red horizontal red ‘laser beam’ line run
down from top to bottom. The part above the line should turn grey and the part underneath
should remain in colour. Make a very short beep sound with each step of the line movement. An
example is shown in Figure 9.22.
various s
positioned a
om here a button appears here
In this book, we take the second approach, and confine the examples and the exercises to using only
the push button object. Like with any object in a MATLAB figure, the properties of the button are
reachable using the get and set commands.
The most important property is the Callback, which determines what the button does when pressed
and released. The Callback can be set as a string in the definition of the button or afterwards, using
the set command. For example,
figure, uicontrol(’Callback’, ’beep’)
will create a button at the bottom left corner of the figure, which will beep (with the unpleasant sound
of a MATLAB error :)) when pressed.
110
CHAPTER 10. GRAPHICAL USER INTERFACES - GUI 111
The callback can be given as a function handle instead of a string. Usually the whole GUI is contained
within one function file. The Callback function must have two compulsory parameters – object and
event. Any input parameter which you want to transmit to the function will be listed next. As an
example, try the code below.
function my_first_gui
figure
for i = 0:9
uicontrol(’Units’, ’Normalized’, ’Position’, [0,i,i+1,1]/9, ...
’BackgroundColor’, rand(1,3), ’Callback’, @long_button)
end
function long_button(o,~)
p = get(o,’Position’);
if p(1) == 0, p(1) = 1-p(3); else p(1) = 0; end
set(o, ’Units’, ’Normalized’, ’Position’, p)
10.2 Examples
Solution.
The code is shown below. The default ‘uicontrol’ object is a push button, so we don’t have to specify
this explicitly. Normalised units are easier to use than pixel units, in order to position the button in
the middle of the figure. The code below includes a choice of font and font size. The Callback consists
of three actions: (1) Generate a new colour as three random values (array t); (2) Set the figure colour
to t; and (3) Set the string if the button to the values in t. For the latter, the values must be converted
from number to string, hence the ‘num2str’ command.
112 CHAPTER 10. GRAPHICAL USER INTERFACES - GUI
figure
uicontrol(’Units’,’Normalized’,’Position’,[0.10 0.45 0.80 0.1],...
’FontName’,’Candara’,’FontSize’,16,’Callback’,...
’t = rand(1,3);set(gcf,’’Color’’,t);set(gco,’’String’’,num2str(t))’);
Note that the code can be shortened by using only the beginning of the words for the properties and
their values. The words can be shortened to the minimum number of letters which eliminates any
ambiguity. For example, ‘Units’ can be shortened to ‘Un’, and ‘Position’ to ’Po’. The font set-up is
optional, so the code can be as follows:
When using string Callbacks, pay particular attention to apostrophes. As MATLAB uses these to delimit
strings, you can end up with broken callbacks. This is why in the previous examples, the apostrophes
are escaped by a second apostrophe.
Figure 10.3: Light colour shapes which progressively darken and disappear with the 7th click.
Shape #4 has been clicked on 4 times
Solution.
Figure 10.4: Thoughts about the solution of the disappearing shapes problem.
Solution.
beep
end
end
time10hits = toc; % time taken for 10 hits
t = text(0.7,0.8,sprintf(’Your time: %.2f s’,time10hits));
set(t,’FontName’,’Candara’,’Fontsize’,16)
10.3 Exercises
1. Spaceship, Moon and Stars
(a) Use the mouse to draw a ‘spaceship’. While the mouse button is being clicked, keep
collecting points. When a key from the keyboard is pressed, fill the ship with grey colour
and set the background to black. (You may need to close the shape manually as the user
may not select the same first and last point).
(b) Upon the next mouse click, plot a moon centred at the position of the mouse.
(c) Plot four constellations centred at the positions of four subsequent mouse clicks. Each
constellation should have 10 stars of different sizes.
2. Create a figure with 26 buttons displaying the letters of the Latin alphabet as shown in
Figure 10.6.
CHAPTER 10. GRAPHICAL USER INTERFACES - GUI 115
When pressed, each button should turn its colour to black. Two randomly chosen buttons should
hide ‘bombs’. When pressed, a bomb button will delete all buttons and turn the figure background
to black.
3. Write a script which displays a panel of 2 rows by 4 columns of push buttons with different
random background colours. (This is possible with one loop!) When a button is pressed, the
title of the panel is changed to the RGB values of the button’s colour, and the background of the
panel is changed to that colour. An example is shown in Figure 10.7.
4. Open a figure with a black background. Create a green push button when the user left clicks
with the mouse. The button should be centred at the point of the mouse click. The button string
should be ‘Press to disappear’. When the button is pressed, the string should disappear, and the
button should shrink in 100 steps towards its centre. Finally, the button should disappear, and
the figure should change its background to green.
5. Create the layout shown in Figure 10.8. When presses, a button should move the whole panel
with 4 buttons in the said direction. The panel should not leave the figure space. When an edge
or a corner is reached, pressing the button for continuing in the same direction should have no
effect.
116 CHAPTER 10. GRAPHICAL USER INTERFACES - GUI
6. Scrabble Helper.
In the game of Scrabble, it is important to have at hand a view of the remaining tiles. The total
number of tiles is 100. There are 27 different tiles: 26 for the letters of the alphabet, and two
empty tiles which can be placed as any letter. The number of tiles for each letter corresponds
roughly to this letter’s frequency in the English language. The letter set, including the 2 empty
tiles at the end, and the corresponding frequencies can be introduced in MATLAB using the two
lines below:
ltf = [9 2 2 4 12 2 3 2 9 1 1 4 2 6 8 2 1 6 4 6 4 2 2 1 2 1 2];
let = [’A’:’Z’,’ ’];
The Scrabble helper should show you the available tiles for a given game. Create a function with
no input arguments. The function should open up a figure with 10× 10 buttons corresponding to
the Scrabble tiles, as shown in Figure 10.9.
Upon pressing, a button should change its background colour. If the colour is light, it should
become dark, and vice versa. In this way, the tiles that have been used in the game are masked
with a dark colour in the figure.
7. Open up a (nearly) square figure. Create 16 square buttons with random colours, as shown in
Figure 10.10 (a). A random ASCII character should be displayed on each button - see Table 7.1.
The characters don’t have to be unique. When pressed, a button should disappear.
One randomly chosen button should have a different behaviour. It should wipe the figure clean
with a black background, and plot 10 ‘fireworks’ at random places and with random colours. Each
‘explosion’ should have 100 rays of different length and direction, as shown in Figure 10.10 (b).
CHAPTER 10. GRAPHICAL USER INTERFACES - GUI 117
(Hint: command ‘randn’ will be useful here.) The firework should be shown consecutively, at
random time intervals, each interval not exceeding 1 second.
8. Write a script which will open a figure and position 4 push buttons in the corners as shown in
Figure 10.11. Initially, fill the four squares with white colour, then square and remove the axes.
When a button is pressed, the respective square is shown in random colour while the remaining
squares are shown in white. (In the example in the Figure, the top right button is pressed.)
Display underneath the figure the RGB values which make up the colour of the non-white
square, as shown.
118 CHAPTER 10. GRAPHICAL USER INTERFACES - GUI
Figure 10.11: Four squares with random colours, one filled at a time
(a) Create a figure with 20 buttons with colours gradually changing from black to yellow, as
shown in Figure 10.12 (a).
(b) When pressed, each button should change its colour to the colour’s complement, that is, the
colour that completes it to white. For example, a colour [0.2, 0.4, 0.1] has a complement [0.8,
0.6, 0.9]. An example is shown in Figure 10.12 (b).
(c) Choose any three random buttons. In addition to changing their colour, when pressed, the
three bottons should do the following. The first button should label the buttons with the
numbers 1-20. The second button will check whether there are numbers on the buttons; if
so, it will shuffle the buttons each time it is pressed. If there are no numbers, the button
will do nothing. The third button will remove the labels from all of the buttons.
(a) (b)
(a) Generate a figure with 20 random triangles in the unit square, filled with random colours
(Figure 10.13). Plot each triangle, only if its area is greater than 0.05. Hint: The area of
triangle with vertices A(a1 , a2 ), B(b1 , b2 ) and C (c1 , c2 ) is;
1
S= × | a1 (b2 − c2 ) + b1 (c2 − a2 ) + c1 (a2 − b2 ) |
2
CHAPTER 10. GRAPHICAL USER INTERFACES - GUI 119
Note: The vertical bars are mathematical ‘jargon’ for the absolute value. This will produce
a positive value even if the result of the expression is negative.
(b) Program the game so that, in order to remove a triangle, you need to click with the mouse
over it. Remove the triangles in reverse order of the way they were generated - i.e. last
triangle goes first or the user must click the ‘top’ triangle each time. If the user clicks
on a different location, i.e. not the triangle whose turn it is to be moved, produce a short
beep-beep sound. The game finishes when all 20 triangles have been removed. To time the
user’s performance, start the clock when the user clicks with the mouse over the figure for
the first time (correct or incorrect click). When the game finishes, show the user’s time in
the centre of the figure as in Figure 10.13 (b).
(a) Plot k random-sized rectangles of random colours at positions indicated with the mouse. At
each click, the respective rectangle should appear in the figure. An example of the output
with k = 15 is shown in Figure 10.14 (a).
(b) Delete a rectangle if the user clicks on it with the mouse. Measure the time from the first
click to the end of the game where all rectangles disappear. Display, in the centre of the
figure, the time taken at the end of the game play.
Begin by displaying a 4-by-5 matrix of black boxes. A random box changes its colour to a random
colour. When the mouse is clicked on that box, the box disappears and a new box changes its
colour. The game finishes when all the boxes disappear from the figure. At the end, the time
taken to remove all the boxes is displayed. An example of the layout is shown in Figure 10.15.
Design a further feature of your choice for this game. This could be sound, text, new rule, new
level, a text window showing the number of wrong clicks, changing background, etc.
120 CHAPTER 10. GRAPHICAL USER INTERFACES - GUI
Figure 10.15: An example of the layout of the Colour boxes game during game play
13. Program a graphical user interface (GUI) as follows. The layout should be as shown in
Figure 10.16. All blocks are push buttons, and start as all grey. When pressed, each button
should change its colour to a random new colour, as shown in the figure. Plant a ‘destroyer’ at
a random position in the matrix. Once the destroyer is pressed, instead of changing colour, the
buttons in its row and in its column are deleted.
(a) Create a GUI figure with 100 push buttons, arranged in 10 rows and 10 columns. Each button
should have a dark random background as shown in the Figure 10.17 (a). The numbers from
1 to 100 should be randomly assigned to the buttons and displayed in white.
(b) Create a game which starts the clock, displays the buttons, and finishes when the player
has pressed all 100 buttons in the correct order, starting with 1, 2, 3, and so on, up to 99,
100. If an incorrect button is pressed, a random two-note sound is made (two beeps with
different random frequencies). If the correct button is pressed, this button is disabled, its
background is turned to white, and a ‘click’ sound is played. A snapshot of the game is
shown in Figure 10.17 (b). When the last button (100) is pressed, the game should wipe out
the figure and show the time elapsed since the start of the game.
15. Create a game similar to the games in the TV show ‘The Cube’.
122 CHAPTER 10. GRAPHICAL USER INTERFACES - GUI
Prepare a figure with a button and a counter set to 0, as shown on in Figure 10.18 (a). Upon
pressing the button ‘Go’, the numbers should start going up towards 100, fairly quickly. The aim
is to stop the counter between 90 and 99 inclusive. The string on the button should change to
‘Stop!’. Pressing the button again should stop the counter and disable the button. If the number
is between 90 and 99 (inclusive), display ‘Well Done!’ as the button string and change the figure
background to green (Figure 10.18 (c)). If the count reaches 100, display a suitable message
and change the figure background to red (Figure 10.18 (d)). After 2 seconds, enable the button,
change the background back to yellow and, change the button string to ‘Play again?’ If the
button is pressed, start the game again.
0 46 96 100
Figure 10.18: Examples of the set-up and the output of the reaction-gauging game featured in the TV
show ‘The Cube’.
16. Use uigetfile to select and load a JPEG image. Create GUI with the layout shown in
Figure 10.19 (a). The top push button should display the original image. The bottom push button
should display the flipped image as shown in Figure 10.19 (b). A green button should indicate
which of the two images is currently shown.
(a) (b)
Load and display a JPEG image. Create handles for the figure and the axes. Create a loop for
selecting a sequence of points on the figure. Plot and join the consecutive points with a yellow
line and a dot marker as shown in Figure 10.20. The loop should run, until a key from the
keyboard is pressed. Collect the points in an array.
Create an animation where an object (for example, a car) moves horizontally from left to right
and back. The figure should contain three buttons as shown in Figure 10.21. Buttons ‘Froward’
and ‘Backward’ should move the object a little, but visible, step in the respective direction. The
middle button, ‘Move’, should cause the object to move from the current position to the right edge,
turn back, move to the left edge, and turn forward again.
Figure 10.21: The GUI set-up for the moving car problem
124 CHAPTER 10. GRAPHICAL USER INTERFACES - GUI
19. Puzzle
Choose an image for the puzzle, upload it and resize it to [240, 300] pixels. Create a grid of 4×5
push buttons which will serve as the puzzle tiles.
Chop the image into 4 rows and 5 columns of 60×60 tiles. Chose a random sequence of showing
the tiles, one at a time. Show the first tile in the window at the bottom right of the grid.
The player’s task is to click on the grid button where the shown tile should be. Selecting a
wrong button has no consequences. If the correct button is pressed, the tile should appear as
the foreground of the button. An example of the mid-game play is shown in Figure 10.22 (b).
Upon placing the penultimate tile, complete the game by putting the last two tiles in place, and
display the player’s time taken to finish the puzzle. An example is shown in Figure 10.22 (c).
Chapter 11
Sounds
11.1 Sounds as Data
Sound is made up by waves which are often simplified to a sine function shown in Figure 11.1. The
sine way is characterised by amplitude, frequency and phase. The phase is important when a sound
contains more than one waves and they are offset by their phases. The amplitude determines how
loud the sound is, and the frequency determines the pitch.
0.5
amplitude samples full oscillation (2π)
signal
-0.5
-1
0 0.2 0.4 0.6 0.8 1
time
Usually sounds are much more complicated than a single sine wave, including many sine-like waves
together. A sound can be reproduced if we find the sine waves it is made up from.
MATLAB command wavread reads Microsoft WAVE (“.wav”) sound file. Figure 11.2 plots two examples:
a chain-saw sound and a 4-short-beeps sound.
Both examples in the figure are sampled with one of the standard frequencies, f s = 8000 (samples per
second). Note: the difference between the signal frequency and the sampling frequency. The sampling
frequency is the number of measurements of the signal that we take per second. The signal frequency
is the number of full sine waves contained within one second (this is measured in a unit called Hertz,
Figure 11.3).
A full piano keyboard is shown in Figure 11.4. The note frequencies are indicated as well.
125
126 CHAPTER 11. SOUNDS
0.5
0
-0.5
-1
0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
4
x 10
0.5
-0.5
-1
500 1000 1500 2000 2500 3000 3500 4000 4500 5000
Less than 1 second
Note frequencies can be calculated from a single frequency, which is usually A from first octave (A4),
f (A) = 440 = f0 Hz. The equation is:
f (n) = f0 × an
where n is the number of half steps away from A. For higher notes n is positive, and for lower notes,
negative. f (n) is the frequency of the note n half steps away. The constant is:
1
a = 2 12 ≈ 1.05946 Hz
Sound can be created as a sine function and played in MATLAB using the sound command. The code
below creates and plays middle A4 for 2 seconds.
Consider another example, where C5 is played for 3 seconds while fading away. In this case the
amplitude should gradually decrease to zero while the frequency will stay unaltered. The code is
shown below. Note the element-wise multiplication where each value of the sine signal is multiplied
by the respective amplitude value.
CHAPTER 11. SOUNDS 127
0 0 0
-1 -1 -1
0 0.2 0.4 0.6 0.8 1 0 0.2 0.4 0.6 0.8 1 0 0.2 0.4 0.6 0.8 1
human cat
12 Hz 40 Hz 20 KHz 79 KHz
To produce a more natural tone, add overtones with smaller amplitudes. Add one overtone with twice
the frequency, which will be an octave higher, and another overtone with half the frequency, which
will be an octave lower. When running the sound command, MATLAB will clip all values of the signal
outside the range [−1, 1]. Therefore, to include overtones, you should use amplitude 0.5 for the base
signal and amplitude 0.25 for both overtones.
11.2 Exercises
1. Utter Noise
(a) Create and play one second of ‘utter noise’ (random values in the interval [−1, 1]).
(b) Insert a pause (zero values) in the interval [0.45, 0.55] of the second.
128 CHAPTER 11. SOUNDS
Middle C (C4)
1480.0
1864.7
1244.5
1108.7
1661.2
830.6
466.2
740.0
370.0
554.4
622.3
932.3
207.7
138.6
103.8
185.0
277.2
155.6
415.3
233.1
116.5
69.3
92.5
58.3
77.8
311.1
2093.0
1760.0
1396.9
1568.0
1046.5
1975.5
880.0
1318.5
698.5
440.0
987.8
1174.7
784.0
246.9
493.9
659.3
329.6
220.0
392.0
349.2
196.0
587.3
293.7
146.8
164.8
130.8
261.6
523.3
174.6
110.0
123.5
98.0
65.4
82.4
87.3
55.0
73.4
61.7
A B C D E F G A B C D E F G A B C D E F G A B C D E F G A B C D E F G A B C
(c) Alter the noise signal to quieten between 0s and 0.45s and progressively raise in amplitude
between 0.55s and 1s.
2. Piano Keyboard
Create a working piano keyboard. All the keys from C4 to C5 should be shown (both the white
and the black ones). Upon pressing a key with the mouse, the respective tone should be played
for 1 second, with the volume fading away. An example of the graphical output is shown in
Figure 11.5.
start CHALLENGE
Write the script for the Piano Keyboard problem using the minimum possible number of lines.
The rules are: (1) Each row has a maximum of 75 symbols. (2) The number of characters does
not matter. (3) The figure must be opened with the figure command. (The authors’ current
record is 5 lines.) Best of luck!
end CHALLENGE
3. Find and download a Wave file of your choice, for example a police siren. Read the signal into
MATLAB using wavread. Modify the signal so that it starts from silence, amplifies to a maximum
and then fades away to silence again.
4. Musical Scales
(a) Write a script to play an ascending musical scale. Each note should be played for 0.8
seconds and should fade linearly. Include overtones.
(b) Add a second melody playing the scale backwards (descending), four times quieter than the
leading melody. The harmony should be played together.
(c) Modify the melody you created in (b) so that it ‘speeds up’. For example, if the first note
lasts 1 second, the last one should last 0.1 seconds.
(d) Plot the first 30 milliseconds of the sound signal in (b). Label the axes and add a title. The
plot should look like the one in Figure 11.6.
1
sound signal
0.5
−0.5
−1
0 5 10 15 20 25 30
time [ms]
Write a script that will compose a piece of music for a horror movie. Here are the rules:
130 CHAPTER 11. SOUNDS
(i) The music should be created with a significant random element in it. This means that you can
re-use parts of the ‘melody’ but there should be random sampling as well.
(ii) All sounds should have proper frequencies, that is frequencies corresponding to existing notes.
The array below contains the allowed frequencies:
Note = [246.94 261.63 277.18 293.66 311.13 329.63 349.23 369.99 392.00 415.30...
440.00 466.16 493.88 523.25];
(iii) The length of the notes should be related to the ‘beat’. If a beat has length h seconds, your
notes may be of size 0.25h, 0.5h, h, 1.5h 2h and 3h. The total length of your piece should be
about 30 seconds. Choose randomly from the lengths and the frequencies until the total length
reaches 30 seconds. Use beat h = 0.5s.
(iv) Use pauses (zeros) in the signal. They may have any of the lengths that other notes may
have.
save(’Horror_Music’,’y’,’fs’)
where y is the variable containing your signal and f s is the sampling frequency. This line will
save variables y and f s in a mat file. If you want to play the piece again later, load the file and
then use sound(y,fs).
Write the function see_music to visualise a music piece. The function should take one input
parameter, the signal y. Split the signal into T equal intervals (for example, T = 2000). For each
interval, calculate an approximation of the pitch (main frequency of the sound) by finding how
many times the signal crosses the x-axis. Plot the T pitches in a complete circle, as shown in
Figure 11.7 for the simple scales. Each interval should be a spoke with length proportional to
the approximated pitch. The pitch does not have to be one of the note frequencies; it will only
serve to trace the pattern of the music piece. The earliest spokes should be dark. The colour
should lighten progressively to a colour of your choice.
Figure 11.8 shows examples of visualisation of five music pieces. (Note that the visualisation is
not required to be animated.)
CHAPTER 11. SOUNDS 131
start
(a) Wolfgang Amadeus Mozart, Piano Sonata No.16 in C Major K.545 (Sonata Facile)
(b) Wolfgang Amadeus Mozart, Serenade no.13 in G major K.525 (Eine Kleine Nachtmusik)
(c) Johann Sebastian Bach, Air on the G String
(d) Johann Sebastian Bach, Ave Maria, harp and violin.
(e) Dubstep, ‘I am waiting for you last summer - Medley season’
Solutions
These are the solutions of problems with even numbers.
• 1.4.4
sqrt((4.172+9.131844)^3-18)/(-3.5+(11.2 - 4.6)*(7-2.91683)^-0.4)
• 1.4.6
Type in the command window log(exp(10)) and then exp(log(10)). Both expressions should
return the value 10.
• 1.4.8
Denote the left-hand side of the equation by f (x). Starting with the middle of the interval (x = 3) find
out in which half the solution lie. For example, check x = 2 next. As both f (3) and f (2) are negative,
the solution must be in [3, 4]. Then keep dividing (and guessing, if you like) to shorten the interval of
the solution until the interval length is 0.1. Return the x such that f (x) and f (x ± 0.1) have different
signs.
>> x=3;
>> 0.5*(x-2)^3 - 40*sin(x)
ans =
-5.1448
>> x=2;
>> 0.5*(x-2)^3 - 40*sin(x)
ans =
132
CHAPTER 12. SOLUTIONS 133
-36.3719
>> x=3.5;
>> 0.5*(x-2)^3 - 40*sin(x)
ans =
15.7188
>> x=3.25;
>> 0.5*(x-2)^3 - 40*sin(x)
ans =
5.3044
>> x = 3.12;
>> 0.5*(x-2)^3 - 40*sin(x)
ans =
-0.1612
>> x = 3.18;
>> 0.5*(x-2)^3 - 40*sin(x)
ans =
2.3574
>> x = 3.14;
>> 0.5*(x-2)^3 - 40*sin(x)
ans =
0.6771
>> x = 3.13;
>> 0.5*(x-2)^3 - 40*sin(x)
ans =
0.2578
Since f (3.12) < 0 and f (3.13) > 0, the solution lies between the two values. Therefore we can return
either of them, say, x = 0.12.
E = {eye(1),eye(2),eye(3),eye(4),eye(5),eye(6),eye(7),eye(8)};
• 2.7.4
First, create the vector with all integers from 1 to 100 by the colon operator and then apply the
command ‘sum’.
sum(1:100)
• 2.7.6
Create arbitrary matrices that can be multiplied as required (ABC ) and calculate the two expressions.
The results should match.
A = [2 3 1;-3 2 5]; % 2-by-3
134 CHAPTER 12. SOLUTIONS
• 2.7.8
v = 20:25;
w = 5*v;
• 2.7.10
a = linspace(1,2*pi,100);
• 2.7.12
First, create a zero matrix A of size 100-by-100 and then replace all values in the even numbered
columns with value 2.
A = zeros(100);
A(:,2:2:100) = 2;
• 2.7.14
• 2.7.16
There are many ways to construct these matrices. For part (a), the matrix is constructed by repeating
a tile of 2 rows. The top row are the numbers from 1 to N, and the second row are the numbers from
N down to 1.
For part (b), the matrix is concatenated from four parts. Then the central pixels are assigned the same
value, different from the values of the four parts.
In part (c), we need to address the edges suitably so that the corners hold the respective colour.
CHAPTER 12. SOLUTIONS 135
• 2.7.18
To find the solution using matrix equation, we should recall that we need the matrix with the coefficients
in frond of the variables (A) and the vector with the right-hand-side values (b):
" # " #
7 −12 −4
A= , b= .
12 −45 −26
• 2.7.20
Suppose m = 4 and n = 3. Using ‘meshgrid’, we can create all row and column indices i and j:
[cols,rows] = meshgrid(1:n,1:m);
rows =
1 1 1
2 2 2
3 3 3
4 4 4
>> cols
cols =
1 2 3
1 2 3
136 CHAPTER 12. SOLUTIONS
1 2 3
1 2 3
Notice that the columns are the x-coordinate, therefore they are the first output arguments of ‘meshgrid’,
and the rows are the second output argument. With these two arrays in place, the code is:
m = 4; n = 3;
[cols,rows] = meshgrid(1:n,1:m);
A = (cols - 4).^2 .* (rows + 1).^-3 + rows.*cols;
A =
• 2.7.22
For part (b), y goes from 1 to 40 while x goes forth and back. We can create one of the upward lines
of x’s, and shift it by 10 to obtain the other. Then we need to merge them like the teeth of two cog
wheels:
x1 = 1:20; % left
x2 = x1 + 10; % right
x(1:2:40) = x1; % insert the left x’s (odd)
x(2:2:40) = x2; % insert the right x’s (even)
y = 1:40;
figure, plot(x,y,’b.-’), grid on
Part (c) is quite similar to part (b). This time y oscillates between 0 and 1. One possible solution
is:
CHAPTER 12. SOLUTIONS 137
x1 = 1:20; % left
x2 = x1 + 10; % right
x(2:2:40) = x1; % insert the left x’s (odd)
x(1:2:40) = x2; % insert the right x’s (even)
y = repmat([0 1],1,20);
figure, plot(x,y,’b.-’), grid on
% third way
x = 1:1000;
disp(x(floor(x/37)==ceil(x/37)))
% fourth way
i = 2;
z = 37;
while z < 1000
disp(z)
z = 37*i;
i = i + 1;
end
• 3.6.4
z = rgb2gray(imread(’peppers.png’)); figure, imshow(z)
z(z<=100) = 0; % black
z(z>100&z<200) = 150; % light grey
z(z>=200) = 255; % white
figure, imshow(z)
• 3.6.6
To check your solution, plug the logical expression you created in the code below, as indicated. For
this wrapper script to work, you need to make sure that your expression allows for vector variables x
and y.
• 3.6.8
NumberToGuess = randi(10);
UserGuess = input(’Please enter your guess -> ’);
if UserGuess == NumberToGuess
disp(’Congratulations! You won!’)
else
disp(’You lost! Better luck next time! The number was’)
disp(NumberToGuess)
end
• 3.6.10
For problem (a), pad array A with one cell on each edge so that each cell of A has 8 neighbours. Then
construct a double loop to go through the rows and the columns of A.
m = 20; n = 30;
A = rand(m,n) < 0.1; % sparse
% A = rand(m,n) < 0.5; % medium
% A = rand(m,n) < 0.7; % dense
B = zeros(m+2,n+2); % padding
B(2:end-1,2:end-1) = A; % inset A
S = 0; % sum of neighbours
for i = 2:m+1
for j = 2:n+1
if B(i,j) % bug
S = S + sum(sum(B(i-1:i+1,j-1:j+1))) - 1; % only neighbours
end
end
end
disp(’Averge number of neighbours per bug:’)
disp(S/sum(B(:)))
Uncomment the other versions of creating A to see how the average number of neighbour bugs
changes.
CHAPTER 12. SOLUTIONS 139
Part (b) can be programmed by checking the neighbourhood for each cell and applying the rule that
fits. The important trick here is not to destroy the current grid A while calculating the ‘tomorrow’s grid.
This is why we use G to store the tomorrow’s bugs calculated from the neighbourhood in A.
A = rand(m,n) < 0.7;
B = zeros(m+2,n+2); % padding
G = B; % the new generation
B(2:end-1,2:end-1) = A; % inset A
for i = 2:m+1
for j = 2:n+1
on = sum(sum(B(i-1:i+1,j-1:j+1))) - B(i,j); % only neighbours
if (B(i,j) && (on == 2 || on == 3)) || (~B(i,j) && on == 3)
G(i,j) = 1;
end
end
end
A = G(2:m-1,2:n-1); % the new generation
Part (c) requires only to include the code from part (b) in loop.
A = rand(m,n) < 0.3;
B = zeros(m+2,n+2); % padding
B(2:end-1,2:end-1) = A; % inset A
figure, spy(B), axis off
figure
for k = 1:50
G = zeros(m+2,n+2); % the clean grid for the new generation
for i = 2:m+1
for j = 2:n+1
on = sum(sum(B(i-1:i+1,j-1:j+1))) - B(i,j); % only neighbours
if (B(i,j) && (on == 2 || on == 3)) || (~B(i,j) && on == 3)
G(i,j) = 1;
end
end
end
B = zeros(m+2,n+2); % padding
B(2:end-1,2:end-1) = G(2:m+1,2:n+1); % new generation
spy(B), axis off
pause(0.2)
end
The glider gun in part (d) is the code in part (c) initialised with the pattern of bugs shown in
Figure 3.9.
m = 25; n = 40;
A = zeros(m,n);
gb = [6,2;6,3;7,2;7,3;6,12;7,12;8,12;5,13;9,13;4,14;10,14;4,15;10,15;...
7,16;5,17;9,17;6,18;7,18;8,18;7,19;4,22;5,22;6,22;4,23;5,23;6,23;...
140 CHAPTER 12. SOLUTIONS
Chapter 4: Functions
• 4.6.2
function D = euclidean_distance_arrays(A,B)
for i = 1:size(A,1)
x = A(i,:); % ith row of A
for j = 1:size(B,1)
y = B(j,:); % jth row of B
D(i,j) = sqrt(sum((x-y).^2));
end
end
Check with:
P = [3 4;1 2]; Q = [-2 5;3 -1; 7 4];
disp(euclidean_distance_arrays(P,Q))
• 4.6.4
CHAPTER 12. SOLUTIONS 141
Here we assume that if the point is on the edge or corner, it is in the square. Check with this
example:
point_in_a_square(0.3,0.8,0,0,1)
point_in_a_square(0.3,1.8,0,0,1)
point_in_a_square(1,0.8,0,0,1)
The first and the third points are in, and the second is out of the unit square.
• 4.6.6
function o = fibo_recursive(k)
if k < 2
o = k;
else
o = fibo_recursive(k-1) + fibo_recursive(k-2);
end
Check with:
for i = 1:10
disp(fibo_recursive(i))
end
end
• 4.6.8
Bubble sort operates by swapping neighbouring elements in the array if they are not in the right order.
It finishes when no swaps are made passing through the whole array.
function A = bubble_sort(A)
SWAP = true;
i = 1;
N = numel(A);
while SWAP
SWAP = false;
for j = 1 : N - i
if A(j) > A(j+1)
A([j,j+1]) = A([j+1,j]);
SWAP = true;
end
end
i = i + 1;
end
Chapter 5: Plotting
• 5.3.2
The script:
figure, hold on, axis equal off
for i = 1:30
plot_circle(rand,rand,rand*0.2,rand(1,3))
end
• 5.3.4
figure, hold on
for i = 1:20
ver = randi([3,6]);
fill(rand(ver,1),rand(ver,1),rand(1,3))
end
axis([0.2 0.8 0.2 0.8])
axis square off
• 5.3.6
function nested_squares(k)
hold on
for i = 1:k
w = k-i+1;
fill([w,w,-w,-w],[-w,w,w,-w],rand(1,3))
end
axis equal off
• 5.3.8
figure, hold on
k = 10; x = [0; rand(k-1,1)]; y = [0; rand(k-1,1)];
% vertex (0,0) is needed for touching in the centre
CHAPTER 12. SOLUTIONS 143
• 5.3.10
(a)
figure, hold on
ind = 1;
h = zeros(1,25);
for i = 1:5
for j = 1:5
h(ind) = fill(rand(1,6)+0.9*i,rand(1,6)+0.9*j,rand(1,3));
ind = ind + 1;
end
end
axis equal off
(b)
figure
subplot(1,2,1), hold on
ind = 1;
X = rand(25,6); Y = rand(25,6); C = rand(25,3); % the forms
for i = 1:5
for j = 1:5
fill(X(ind,:)+0.9*i,Y(ind,:)+0.9*j,C(ind,:));
ind = ind + 1;
end
end
axis equal off
title(’Original’)
subplot(1,2,2), hold on
% permute the figures
rp = randperm(25); X = X(rp,:); Y = Y(rp,:); C = C(rp,:);
ind = 1;
for i = 1:5
for j = 1:5
fill(X(ind,:)+0.9*i,Y(ind,:)+0.9*j,C(ind,:));
ind = ind + 1;
end
end
axis equal off
title(’Shuffled’)
• 5.3.12
144 CHAPTER 12. SOLUTIONS
% (a)
figure, hold on
T = 5;
for i = 1:T
plot([0 i 0 -i 0],[-i 0 i 0 -i],’k-’,’color’,[i 0 0]/T,’linewidth’,5)
end
axis equal off
% (b)
figure, hold on
T = 100;
for i = 1:T
if i <= T/2
plot([0 i 0 -i 0],[-i 0 i 0 -i],’k-’,...
’color’,2*[0 i 0]/T,’linewidth’,5)
else
plot([0 i 0 -i 0],[-i 0 i 0 -i],’k-’,...
’color’,[0 0 i-T/2]/(T/2),’linewidth’,5)
end
end
axis equal off
• 5.3.14
(a)
function draw_balloon(x,y,r,c,l)
t = linspace(0,2*pi,100);
fill(sin(t)*r + x, cos(t)*r + y, c) % draw balloon
(b)
figure, hold on, axis equal off
for i = 1:20
CHAPTER 12. SOLUTIONS 145
(c)
figure, hold on, axis equal off
for i = 1:20
ra = rand*0.1+0.05; % radius
draw_balloon(rand, 1-ra, ra, rand(1,3), rand*0.3+0.3)
end
v = axis;
fill([v(1) v(2) v(2) v(1)],[v(4) v(4) v(4)+0.1 v(4)+0.1],[0.7 0.7 0.7])
Chapter 6: Data
• 6.4.2
a = randn(30,1)*20 + 100;
• 6.4.4
Note that the expression in the parentheses can be calculated as a single constant. The
expression was left in this form here for readability. The random number should be multiplied
by the (max - min) and then the minimum should be added.
(b) Generate an array A of size 20-by-20 of random integers in the interval [−40, 10]. Subsequently,
replace by 0 all elements of A which are smaller than k.
A = randi([-40, 10],20);
A(A < k) = 0;
(e) Visualise A using a random colour map containing exactly as many colours as there are different
elements of A.
146 CHAPTER 12. SOLUTIONS
(f) Extract 4 different random rows from A and save them in a new array B.
r = randperm(size(A,1),4); % rows # to extract
B = A(r,:);
(h) Display in the Command Window the answers of (a), (c), (d) and (g) with a proper description of
each one.
disp(’A random number between -30.4 and 12.6:’), disp(k)
disp(’Mean of all non-zero elements of A:’), disp(mnzA)
disp(’A random element of A:’), disp(rndA)
disp(’Proportion of non-zero elements of B:’), disp(propnzB)
• 6.4.6
1. Generate an array of 10,000 random outcomes of the three slots of the machine.
outcomes = randi(6,10000,3);
2. Find the total number of winning combinations among the 10,000 outcomes.
wins = sum(outcomes(:,1) == outcomes(:,2) & ...
outcomes(:,1) == outcomes(:,3));
3. Assume that the entry fee for each run is 1 unit of some imaginary currency. Each winning
combination is awarded a prize of 10 units except for the combination of three 1s, which is
awarded a prize of 50. Assuming you are the owner of the slot machine, calculate your profit
after the 10,000 runs of the game.
win_index = outcomes(:,1) == outcomes(:,2) & ...
outcomes(:,1) == outcomes(:,3);
profit = 10000 - sum((win_index & outcomes(:,1) ~= 1) * 10) - ...
sum((win_index & outcomes(:,1) == 1) * 50);
disp(’Profit = ’), disp(profit)
CHAPTER 12. SOLUTIONS 147
• 6.4.8
a = randn(5000,2);
ind = sqrt(a(:,1).^2+a(:,2).^2) < 0.7 | sqrt(a(:,1).^2+a(:,2).^2) > 1.5;
figure
plot(a(ind,1),a(ind,2),’g.’)
axis equal, grid on
• 6.4.10
a = randn(1,1000).*(1:1000)*0.2; % random signal with increasing amplitude
y_offset = linspace(-400,200,1000); % increasing slope to add
s = a + y_offset; % the signal
[mins,ind_mins] = min(s);
[maxs,ind_maxs] = max(s);
• 6.4.12
figure, grid on
fill([0 1 1 7 7 5 5 0],[1 1 8 8 9 9 5 5],[0.7 0.7 0.7])
x = rand(1000,1) * 7;
y = rand(1000,1) * 8 + 1;
index = (x > 0) & (x < 1) & (y > 1) & (y < 5) | ...
(x > 1) & (x < 5) & (y > 5) & (y < 8) | ...
(x > 5) & (x < 7) & (y > 8) & (y < 9);
hold on
plot(x(index),y(index),’k.’)
• 6.4.14
x = rand(2000,1) * 200 - 35;
y = rand(2000,1) * 100 - 20;
index1 = ((x - 30).^2 + (y - 40).^2 < 900) | ...
((x + 10).^2 + y.^2 < 1600);
index2 = ((x - 30).^2 + (y - 40).^2 < 64) | ...
((x + 10).^2 + y.^2 < 64);
figure, hold on
plot(x(~index1&~index2),y(~index1&~index2),’k.’,’markersize’,15,...
’color’,[0.7 0.7 0.7])
plot(x(index1&~index2),y(index1&~index2),’rx’,’linewidth’,2.5,...
’markersize’,10)
plot(x(index2),y(index2),’g+’,’linewidth’,2.5,’markersize’,10)
148 CHAPTER 12. SOLUTIONS
• 6.4.16
(a)
k = 10; % range of the matrix entry
T = 10000; % number of iterations
count = 0;
for i = 1:T
m = randi([-k k],2);
if det(m) == 0 % singularity check
count = count + 1;
end
end
fprintf([’Proportion of singular 2x2 integer-valued matrices in ’,...
’[-%i,%i]: %.4f\n’],k,k,count/T)
(b)
c = zeros(1,50);
for k = 1:50
count = 0;
for j = 1:T
m = randi([-k k],2);
if det(m) == 0
count = count + 1;
end
end
c(k) = count;
end
figure
plot(c/T,’k-’)
grid on
title(’Proportion of singular 2x2 matrices with integer entries in [-k,k]’)
xlabel(’k’)
The output is shown in Figure 12.1. The proportion of singular 2-by-2 matrices with integers between
−k and k decreases exponentially with increasing k.
• 6.4.18
(a)
% checking for three-of-a-kind
Values = {’1’,’2’,’3’,’4’,’5’,’6’,’7’,’8’,’9’,’10’,’J’,’Q’,’K’};
Suits = {’C’,’D’,’H’,’S’};
CardValue = zeros(1,5);
k = 0; % counter
while sum(CardValue==max(CardValue)) ~= 3 || numel(unique(CardValue)) ~=3
k = k + 1;
CHAPTER 12. SOLUTIONS 149
(b)
% evaluating a hand
Values = {’A’,’2’,’3’,’4’,’5’,’6’,’7’,’8’,’9’,’10’,’J’,’Q’,’K’};
Suits = {’C’,’D’,’H’,’S’};
ph = {’high card’,’one pair’,’two pairs’,’three of a kind’,’straight’,...
’flush’,’full house’,’four of a kind’,’straight flush’};
disp(ph{r})
• 6.4.20
(a)
cx = randi(10); cy = randi(10); r = randi(10);
bx = randi(10); by = randi(10); w = randi(10); h = randi(10);
(b)
figure, hold on, axis equal, grid on
theta = linspace(0,2*pi,100);
plot(sin(theta)*r+cx,cos(theta)*r+cy,’b-’,’linewidth’,2) % plot circle
Rx = [bx,bx+w,bx+w,bx,bx]; Ry = [by,by,by+h,by+h,by];
plot(Rx,Ry,’b-’,’linewidth’,2) % plot rectangle
(c)
% check whether to calculate or simulate
R = [Rx’ Ry’];
T = [];
if all(sum((R - repmat([cx,cy],5,1)).^2,2) < r^2) % rectangle within
ar = w * h; % area
elseif cx-r>=bx && cx+r<=bx+w && cy-r>=by && cy+r<=by+h % circle within
ar = pi * r^2;
else
T = 30000; % number of points for the Monte Carlo simulation
% generate points within the tight square around the circle
x = rand(T,1)*2*r+cx-r; y = rand(T,1)*2*r+cy-r;
% find the number within the intersection
in_rectangle = x>bx & x<bx+w & y>by & y<by+h;
in_circle = (x-cx).^2 + (y-cy).^2 - r^2 < 0;
ind = in_rectangle & in_circle;
number_in = sum(ind);
ar = number_in/T * (2*r)^2;
end
(d)
figure, hold on, axis equal, grid on
if T % area has been estimated (not calculated)
plot(x,y,’k.’,’markersize’,2)
plot(x(ind),y(ind),’r.’,’markersize’,8)
end
title([’Area = ’,num2str(ar)])
plot(sin(theta)*r+cx,cos(theta)*r+cy,’b-’,’linewidth’,2) % plot circle
plot(Rx,Ry,’b-’,’linewidth’,2) % plot rectangle
• 6.4.22
152 CHAPTER 12. SOLUTIONS
• 6.4.24
figure
P = rand(25) > 0.4;
directions = [1 0;0 1;-1 0;0 -1]; % for possible moves
k = 0; % counter of the steps
while sum(sum(P)) > 0 % bugs left
W = zeros(25); % new canvas
for i = 1:25
for j = 1:25
if P(i,j) % bug
move = ceil(rand*4);
CHAPTER 12. SOLUTIONS 153
• 6.4.26
The function:
function [p,d] = greedy_tsp(cities)
n = size(cities,1); di = zeros(n);
for i = 1:n-1
for j = i+1:n
di(i,j) = sum((cities(i,:) - cities(j,:)).^2);
di(j,i) = di(i,j);
end
end
di = sqrt(di);
d = 0;
p = 1; % cities visited
cn = 2:n; % cities not visited yet
for i = 1:n-1
[sd,next_city] = min(di(cn,p(end)));
d = d + sd; % add the smallest distance sd
p = [p, cn(next_city)]; % add the new city to the list
cn(next_city) = []; % remove the new city from non-visited
end
d = d + di(p(end),1);
[g,dg] = greedy_tsp(ci);
figure, hold on
plot([ci(g,1);ci(g(1),1)],[ci(g,2);ci(g(1),2)],...
’go-’,’linewidth’,2,’markersize’,12);
plot([ci(g,1);ci(g(1),1)],[ci(g,2);ci(g(1),2)],...
’ro’,’linewidth’,2,’markersize’,8);
axis square, grid on
title([’GREEDY Minimum d = ’,num2str(dg)])
Chapter 7: Strings
• 7.4.2
s = [’Try to distinguish between e-mail addresses ending with "uk", ’...
’and those ending with something else. For example, check with ’,...
’[email protected] and print out the result.’];
[first_part,second_part] = strtok(s,’@’);
blanks_first_part = strfind(first_part,’ ’);
address1 = first_part(blanks_first_part(end)+1:end);
blanks_second_part = strfind(second_part,’ ’);
address2 = second_part(1:blanks_second_part(1)-1);
dots = strfind(address2,’.’);
network_extension = address2(dots(end)+1:end);
address = [address1 address2];
if strcmp(network_extension,’uk’)
fprintf(’UK address: %s\n’,address)
else
fprintf(’non-UK address: %s\n’,address)
end
% Change "[email protected]" to "[email protected]"
% and run this part of the code again
• 7.4.4
s = input(’And you were saying?... ’,’s’);
% Explain how this next line works ... :)
fprintf(’Really, %s?\n’,fliplr(strtok(fliplr(s))))
• 7.4.6
(a)
s = [’Once upon a time, a very long time ago now, about last Friday, ’,...
’Winnie-the-Pooh lived in a forest all by himself under the ’,...
’name of Sanders. "What does ’’under the name’’ mean?" asked ’,...
’Christopher Robin. "It means he had the name over the door in ’,...
’gold letters, and lived under it."’];
(b)
CHAPTER 12. SOLUTIONS 155
s = strrep(s,’Winnie-the-Pooh’,’Dawn French’);
s = strrep(s,’Sanders’,’Stephen King’);
s = strrep(s,’Christopher Robin’,’Bahama Mama’);
(c)
N1 = numel(s);
N2 = sum(s~=’ ’);
fprintf(’The string contains %i characters if counting the spaces\n’,N1)
fprintf(’and %i characters without the spaces.\n\n’,N2)
(d)
fprintf(’The total number of words is %i.\n\n’,N1-N2+1)
• 7.4.8
C = {’Albania’;’Andorra’;’Austria’;’Belarus’;’Belgium’;...
’Bosnia and Herzegovina’;’Bulgaria’;’Croatia’;’Cyprus’;...
’Czech Republic’;’Denmark’;’Estonia’;’Finland’;...
’France’;’Germany’;’Greece’;’Hungary’;’Iceland’;...
’Ireland’;’Italy’;’Kosovo’;’Latvia’;’Liechtenstein’;...
’Lithuania’;’Luxembourg’;’Malta’;’Moldova’;’Monaco’;...
’Montenegro’;’Netherlands’;’Norway’;’Poland’;...
’Portugal’;’Republic of Macedonia’;’Romania’;...
’Russia’;’San Marino’;’Serbia’;’Slovakia’;...
’Slovenia’;’Spain’;’Sweden’;’Switzerland’;...
’Turkey’;’Ukraine’;’United Kingdom’;’Vatican City’};
S = upper(C{randi(numel(C))});
SS = S(randperm(length(S)));
InputString = sprintf([’Anagram of a European country --%s--’,...
’.\nYour guess? --> ’],SS);
trial = 1;
while trial < 4
UserC = input(InputString,’s’);
if strcmpi(UserC,S) % compare the string ignoring the case !!!
fprintf(’\n\nCongratulations! %s is correct!\n\n’,S)
break
else
trial = trial + 1;
if trial == 4 % exit with no success
disp([’GAME OVER! The country was ’ S ’.’])
else
fprintf(’Not correct. Try again!\n’)
end
end
end
156 CHAPTER 12. SOLUTIONS
• 7.4.10
function M = LaTeX_matrix(A)
% outputs a string array with the LaTeX syntax for matrix A
[m,n] = size(A);
s = ’\\left[\\begin{array}\n{’;
for i = 1:n, s = [s,’r’]; end
s = [s,’}’];
for i = 1:m
s1 = ’’;
for j = 1:n
s1 = [s1,’%d&’];
end
s1 = [s1(1:end-1), ’\\\\\n’];
s = [s, s1];
end
s = [s,’\\end{array}\\right]’];
A = A’;
M = sprintf(s,A(:)’);
Chapter 8: Images
• 8.4.2
House =[
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 1 0 0 0 0 0 0 0
0 0 0 0 0 1 1 1 1 0 0 0 0 0 0
0 0 0 0 1 1 1 1 1 1 0 0 0 0 0
0 0 0 1 1 1 1 1 1 1 1 0 0 0 0
0 0 0 0 3 3 3 3 3 3 0 0 0 0 0
2 2 2 2 3 4 3 3 3 3 2 2 2 2 2
2 2 2 2 3 4 3 4 4 3 2 2 2 2 2
2 2 2 2 3 3 3 4 4 3 2 2 2 2 2
2 2 2 2 3 3 3 4 4 3 2 2 2 2 2
];
house = [
0 0 1 % blue
1 0 0 % red
0 1 0 % green
0.8 0.8 0.8 % grey
0 0 0 % black
];
f = figure;
CHAPTER 12. SOLUTIONS 157
imagesc(House);
colormap(house)
axis equal off
• 8.4.2
A = imread(’BabyC.jpg’);
ti = {’Red’,’Green’,’Blue’};
figure
for i = 1:3
subplot(3,1,i)
p = A(:,:,i); hist(double(p(:)),50);
title(ti{i})
grid on
if i == 1, axis tight, v = axis; else axis(v), end
end
• 8.4.6
A = imread(’bangor.jpg’);
B = A*0.3;
figure, imshow(255*0.7+B)
The script
A = imread(’JazzieSleepTail.jpg’);
B = [randomise_image_panel(A,’R’),randomise_image_panel(A,’G’),...
randomise_image_panel(A,’B’),];
figure(’Position’,[100,100,800,220]),imshow(B)
• 8.4.10
A = rgb2gray(imread(’Joey.jpg’)); % read image and convert to grey
for i = 1:6
B = imresize(A,.5);
A(1:size(B,1),1:size(B,2)) = B; % resize and inset
end
figure, imshow(A)
• 8.4.12
A = imread(’Joey.jpg’);
s = size(A);
midR = round(s(1)/2); midC = round(s(2)/2);
A(1:midR,1:midC,1) = 255; % red top left
A(1:midR,midC+1:end,3) = 255; % blue top right
158 CHAPTER 12. SOLUTIONS
• 8.4.14
A = imread(’joey_and_robot.jpg’);
figure, imshow(A)
s = size(A);
lw = ceil(s(1)/200);
tenrows = round(linspace(1,s(1)-lw,11));
tencolumns = round(linspace(1,s(2)-lw,11));
B = A;
for i = 1:lw
B(tenrows+i-1,:,:) = 0;
B(tenrows+i-1,:,2) = 255;
B(:,tencolumns+i-1,:) = 0;
B(:,tencolumns+i-1,2) = 255;
end
figure, imshow(B)
• 8.4.16
The function:
function Im = shuffle_image(A,M,N)
if ndims(A)==2 %#ok<*ISMAT>
A = cat(3,A,A,A); % make a grey image into rgb
end
Rows = floor(size(A,1)/M);
Columns = floor(size(A,2)/N);
Im = uint8(zeros(size(A)));
% Shuffle index
RP = reshape(randperm(M*N),M,N);
k = 1;
for i = 1:M
for j = 1:N
T = A((i-1)*Rows + 1 : i*Rows,...
(j-1)*Columns + 1 : j*Columns,:); % take current block
[new_r,new_c] = find(RP == k);
Im((new_r-1)*Rows + 1 : new_r*Rows,...
(new_c-1)*Columns + 1 : new_c*Columns,:) = T; % position
% in the new row/column
k = k + 1;
end
end
CHAPTER 12. SOLUTIONS 159
The script:
A = imread(’winter_mountain.jpg’);
B = shuffle_image(A,4,5);
figure,imshow(A)
figure,imshow(B)
• 8.4.18
The function:
function [p,q,r] = words_around_shape(C,mode)
N = numel(C);
if mode == 1
C = sort(C);
end
hold on
axis([-2 2 -2 2])
axis square off
t = 2 * pi / N;
Co = [0; 1];
R = [cos(t) sin(t);-sin(t) cos(t)];
for i = 1:N
r(i) = text(Co(1),Co(2),C{i},’Rotation’,90 - t*(i-1)/pi*180);
q(i) = plot([0 Co(1)],[0 Co(2)]);
Co1 = R * Co;
p(i) = plot([Co(1) Co1(1)],[Co(2) Co1(2)]);
Co = Co1;
end
• 8.4.20
A = double(imresize(imread(’winter_mountain.jpg’),0.05));
r = A(:,:,1); g = A(:,:,2); b = A(:,:,3);
figure, hold on
set(gca,’FontName’,’Candara’,’FontSize’,12)
grid on
scatter3(r(:),g(:),b(:),6,[r(:),g(:),b(:)]/255,’filled’)
rotate3d
Chapter 9: Animation
• 9.4.2 Highlight
A = imread(’ConnorsCars2.jpg’);
r = A(:,:,1); g = A(:,:,2); b = A(:,:,3);
160 CHAPTER 12. SOLUTIONS
figure, imshow(A)
waitforbuttonpress
t = get(gca,’CurrentPoint’);
% create mask
[x,y] = meshgrid(1:size(r,2),1:size(r,1));
ra = 600; % radius of the region of interest
mask = (x-t(1,1)).^2 + (y-t(1,2)).^2 < ra^2;
r(~mask) = r(~mask)*0.5;
g(~mask) = g(~mask)*0.5;
b(~mask) = b(~mask)*0.5;
B = uint8(cat(3,r,g,b));
figure,imshow(B)
• 9.4.6 Stopwatch
S = input(’Number of seconds? ---> ’);
figure(’color’,’y’)
hold on
text(-0.10,0.95,’Stopwatch’,’FontName’,’Tempus Sans ITC’,’Fontsize’,20);
t = text(0.2,0.5,’0’,’FontName’,’Tempus Sans ITC’,’Fontsize’,140);
axis off
for i = 1:S
set(t,’String’,num2str(i))
pause(0.98)
end
plot(sin(theta)*r2,cos(theta)*r2,’k--’)
theta1 = linspace(0,4*pi,250);
theta2 = linspace(0,4*pi,500);
h1 = plot(0,1,’r.’,’markersize’,50); % planet 1 (inner)
h2 = plot(0,3,’b.’,’markersize’,40); % planet 2 (outer)
h3 = plot(sin(theta)*0.8,cos(theta)*0.8+r2,’k--’); % orbit of moon
h4 = plot(sin(theta(30))*0.8,cos(theta(30))*0.8+r2,’k.’,...
’markersize’,30); % moon of planet 2
axis([-4 4 -4 4])
axis square off
for i = 1:500
set(h1,’Xdata’,r1*sin(theta1(mod(i,250)+1)),...
’Ydata’,r1*cos(theta1(mod(i,250)+1)))
set(h2,’Ydata’,r2*sin(theta2(mod(i,500)+1)),...
’Xdata’,r2*cos(theta2(mod(i,500)+1)))
set(h3,’Ydata’,r2*sin(theta2(mod(i,500)+1))+cos(theta)*0.8,...
’Xdata’,r2*cos(theta2(mod(i,500)+1))+sin(theta)*0.8)
% fixed moon
% set(h4,’Ydata’,r2*sin(theta2(mod(i,500)+1))+cos(theta(30))*0.8,...
% ’Xdata’,r2*cos(theta2(mod(i,500)+1))+sin(theta(30))*0.8)
% orbiting moon
set(h4,’Ydata’,r2*sin(theta2(mod(i,500)+1))+cos(theta2(i))*0.8,...
’Xdata’,r2*cos(theta2(mod(i,500)+1))+sin(theta2(i))*0.8)
pause(0.02)
end
hold on
axis([-1 1 -1 1])
axis square off
theta = linspace(0,2*pi,N+1);
r = linspace(bw,Co(1),N);
g = linspace(bw,Co(2),N);
b = linspace(bw,Co(3),N);
for i = 1:N
fill([0 cos(theta(i)) cos(theta(i+1)) 0],...
[0 sin(theta(i)) sin(theta(i+1)) 0], [r(i),g(i),b(i)])
pause(0.1)
end
end
subplot(2,2,4), imshow(D)
set(gca,’FontName’,’Candara’,’FontSize’,12)
title(’Reveal’)
for j = 10:-1:1
for i = 1:10
uicontrol(’Un’,’N’,’Pos’,[i-1,j-1,1,1]/10,’Str’,to_show(k),...
’FontName’,’Candara’,’FontSize’,18,...
’ForegroundColor’,[0.8 0.4 0.4],’Callback’,...
’co = get(gco,’’Ba’’);set(gco,’’Ba’’,1 - co)’);
k = k + 1;
end
end
j = 20;
while j > 0
k = waitforbuttonpress;
166 CHAPTER 12. SOLUTIONS
hh = gco;
if k == 0
if j == 20
tic
end
if hh == h(j)
set(hh,’visible’,’off’)
j = j - 1;
else
sound(y,fs)
end
end
end
t = toc;
fill([0 1 1 0],[0 0 1 1],[0.8 0.8 0.8],’edgecolor’,’none’)
tt = text(0.25,0.5,sprintf(’Your time is %.2f s.\n’,t));
set(tt,’FontName’,’Candara’,’FontSize’,18)
A = imread(’YellowCar.jpg’);
h = axes(’position’,[0.02,0.5,0.3,0.1]);
imshow(A)
b(1) = uicontrol(’Un’,’N’,’Pos’,[0.05,0.05,0.25 0.1],’Str’,’Backward’,...
’Callback’,[’p = get(h,’’Pos’’);,’,...
’set(h,’’Pos’’,[max(p(1)-0.01,0),p(2),p(3),p(4)])’]);
b(2) = uicontrol(’Un’,’N’,’Pos’,[0.7,0.05,0.25 0.1],...
’Str’,’Forward’,...
’Callback’,[’p = get(h,’’Position’’);,’,...
’set(h,’’Position’’,[min(1-p(3),p(1)+0.01),p(2),p(3),p(4)])’]);
b(3) = uicontrol(’Un’,’N’,’Position’,[0.4,0.05,0.2 0.1],...
’Str’,’Move’,’Callback’,’move_the_car’);
set(b,’FontN’,’Tempus Sans ITC’,’FontS’,18,’Ba’,[0 0 0],’For’,[1 1 1])
This code requires a file with the Callback for the Move button with name move_the_car.m
p = get(h,’Position’);
while p(1)+p(3) < 1
set(h,’Position’,[p(1)+0.005,p(2),p(3),p(4)])
p = get(h,’Position’);
pause(0.005);
end
CarFlip(:,:,1) = fliplr(A(:,:,1));
CarFlip(:,:,2) = fliplr(A(:,:,2));
CarFlip(:,:,3) = fliplr(A(:,:,3));
imshow(CarFlip)
p = get(h,’Position’);
while p(1)-0.01 > 0
set(h,’Position’,[p(1)-0.005,p(2),p(3),p(4)])
p = get(h,’Position’);
pause(0.005);
end
imshow(A)
figure(’Units’,’Normalized’,’Position’,[1 1 4 6]*.1)
f = 440*2.^((-9:3)/12); % note frequencies
r = [2 4 0 7:2:11];
for i = [1 2 4 5 6] % black keys
uicontrol(’Un’,’N’,’Pos’,[.6+i,3.4,.7,5.6]/10,’Ba’,’k’,...
’Callback’,{@n,(f(r(i)))});
end
function n(~,~,F)
fs = 6^5;
T = 1;
t = 0:1/fs:T;
sound((T-t)/T.* sin(2*pi*t*F),fs)
end
end
(a)
y = [];
T = 1; % time in seconds
t = 0:1/fs:T;
A = (T - t) / T; % fading amplitude
for i = 1:8
no = noteFrequency(i);
s = A .* (sin(2*pi*t*no) + 0.2*(sin(pi*t*no) + sin(4*pi*t*no)));
y = [y, 0 s];
end
sound(y,fs)
(b)
y = [];
T = 1;
t = 0:1/fs:T;
A = (T - t) / T;
for i = 1:8
no = noteFrequency(i);
noback = noteFrequency(9-i);
s1 = A .* (sin(2*pi*t*no) + 0.2*(sin(pi*t*no) + sin(4*pi*t*no)));
s2 = A .* (sin(4*pi*t*noback) + 0.2*(sin(2*pi*t*noback) + ...
sin(8*pi*t*noback)));
y = [y, 0 0.8 * s1 + 0.2 * s2];
end
sound(y,fs)
%wavwrite(y,fs,’scales_harmony.wav’)
yb = y; % save the signal for the plot in 2(d)
170 CHAPTER 12. SOLUTIONS
(c)
y = [];
T = linspace(1,0.1,8);
fs = 8000;
for i = 1:8
t = 0:1/fs:T(i);
no = noteFrequency(i);
noback = noteFrequency(9-i);
A = (T(i) - t) / T(i); % amplitude is specific for duration T(i)
no = noteFrequency(i);
noback = noteFrequency(9-i);
s1 = A .* (sin(2*pi*t*no) + 0.2*(sin(pi*t*no) + sin(4*pi*t*no)));
s2 = A .* (sin(4*pi*t*noback) + 0.2*(sin(2*pi*t*noback) + ...
sin(8*pi*t*noback)));
y = [y, 0 0.8 * s1 + 0.2 * s2];
end
sound(y,fs)
(d)
% fs per second, fs/1000 per milisecond, round(30*fs/1000) per 30 ms
N = round(30*fs/1000); % number of samples corresponding to 30 ms
X = linspace(0,30,N); % prepare x-axis
figure, plot(X,yb(1:N),’k-’)
set(gca,’FontName’,’Candara’,’FontSize’,12)
title(’The first 30 ms of the harmony scale signal’)
xlabel(’time [ms]’)
ylabel(’sound signal’)
The function:
function see_music(y)
N = numel(y);
T = 2000;
hos = floor(N/T); % split into T pieces
ints = floor(N/hos);
y = y(1:ints*hos); % truncate to a multiple of hos
r = reshape(y,hos,[]); % arrange consecutive intervals of length hos
pf = mean(abs(diff(r>0))); % find a proxy for the frequencies
Q = linspace(0,2*pi,T);
figure, hold on
for i = 1:min(ints,T)
plot([0 pf(i)*sin(Q(i))],[0 pf(i)*cos(Q(i))],’k-’,’color’,[0 i/ints 0])
end
axis equal off
load handel
see_music(y)
Index
.* Hadamard Product, 5, 16 global, 39 rand, 12, 13, 31, 34, 45, 53, 56,
glyphplot, 54 113
all, 26 gray2ind, 83 randi, 53
any, 26 randn, 53, 63
axis, 11, 44, 45 handles, 95 randperm, 53, 63, 71
hist, 54 range, 54
bar, 54 hold, 44, 45 relational operations, 24, 56
bubble sort, 40 repmat, 11, 12, 16, 29, 44, 72,
i, 8 79
case, 27 if, 23, 26 reshape, 12, 16
ceil, 5, 72 imagesc, 5, 11, 20, 81 rgb2gray, 31, 81, 82
cell array, 17 imread, 21, 31, 81, 82 round, 5
challenge, 52, 59, 92, 97, 129 imresize, 83
clc, 3 imshow, 21, 31, 78, 79, 81, 82 save, 63
clear all, 3 indexing, 10, 17, 30, 31, 71, 72 set, 95, 110, 113
close all, 3 Inf, 8 sin, 4, 5, 16, 38, 45, 126
colon operator, 13, 27, 30, 45, 71, 72, 82, inline, 38 size, 8, 16, 31, 82
100, 126 input, 32, 70 sort, 16
colormap, 81 inv, 16 sound, 100, 126
cos, 4, 5, 16, 45 isempty, 26, 113 sprintf, 70, 72
ismember, 26 spy, 78
delete, 113 isstr, 70 sqrt, 4–6, 16
diary, 3 std, 54
disp, 7, 27, 70, 72 length, 72 str2num, 70
linewidth, 45 strcmp, 70
edgecolor, 45 linspace, 14 strfind, 70
else, 26 log, 4, 16 strrep, 70
elseif, 26 logical indexing, 10, 25, 82 strtok, 70
eps, 8 logical operations, 23, 24 strtrim, 70
exist, 26 sum, 16
exp, 4, 6, 16, 38 markersize, 44 switch, 27
eye, 12, 13, 78 max, 16
mean, 54 tic, 100, 102
Fibonacci, 40 median, 54 tilde symbol, 36
figure, 41 meshgrid, 14, 80 toc, 100, 102
fill, 42, 45, 100 min, 16, 36
fille, 45 mode, 54 uicontrol, 110, 112, 113
find, 16, 31, 113 uint8, 21
fliplr, 16, 45 NaN, 8 unique, 16
flipud, 16 numel, 16, 30, 31
floor, 5 var, 54
for, 27, 30, 45, 56, 100, 111 ones, 12, 13
fprintf, 71 waitforbuttonpress, 96, 113
function, 36 pause, 96 while, 27, 29, 31
function handle, 39, 111 pi, 8
pie, 54 xor, 23
get, 95, 110, 111, 113 plot, 41, 44, 56, 95, 100
ginput, 97 plot3, 92 zeros, 12, 13, 113
172