Anda di halaman 1dari 93

Lecture notes

Digital Image Processing by Jorma Kekalainen

Digital Image Processing


Jorma Kekalainen

Digital Image Processing


Basics of Matlab

Lecture weeks 5 and 6

Page 1

Lecture notes

Digital Image Processing by Jorma Kekalainen

Introduction
MATLAB is a data analysis and visualization tool which
has been designed with powerful support for matrices
and matrix operations.
Also Matlab has its own powerful programming
language and excellent graphics capabilities.
One of the reasons that Matlab has become such an
important tool is through the use of sets of Matlab
programs designed to support a particular task.
These sets of programs are called toolboxes, and here
the particular toolbox of interest to us is the image
processing toolbox.
Jorma Kekalainen

Digital Image Processing

204

Functions and commands


Rather than give a description of all of Matlab's capabilities, we
shall introduce functions, commands and techniques as required.
A Matlab function is a keyword which accepts various parameters,
and produces some sort of output: for example a matrix, a string, a
graph or figure.
Examples of such functions are sin, imread.
There are many ready made functions in Matlab, but it sometimes
necessary to write our own.
A command is a particular use of a function.
Examples of commands might be
>>sin(pi/3)
>>c=imread('cameraman.tif');

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

205

Page 2

Lecture notes

Digital Image Processing by Jorma Kekalainen

Matlab's standard data type


Matlab's standard data type is the matrix -- all
data are considered to be matrices of some sort.
Images, of course, are matrices or stack of
matrices whose elements are the gray values (or
possibly the RGB values) of its pixels.
Single values are considered by Matlab to be
(1*1) matrices, while a string is merely a (1*n)
matrix of characters; n being the string's length.

Jorma Kekalainen

Digital Image Processing

206

Command window
When we start up Matlab, we have a blank
window called the Command window in
which we enter commands.
Command Window is shown in the following
figure.
The prompt consists of two right arrows:
>>

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

207

Page 3

Lecture notes

Digital Image Processing by Jorma Kekalainen

Command window ready for action

Jorma Kekalainen

Digital Image Processing

208

Desktop panels
The desktop includes these panels:
Current Folder Access your files.
Command Window Enter commands at the
command line, indicated by the prompt (>>).
Workspace Explore data that you create or
import from files.
Command History View or rerun
commands that you entered at the command
line.
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

209

Page 4

Lecture notes

Digital Image Processing by Jorma Kekalainen

Current Folder

Jorma Kekalainen

Digital Image Processing

210

Command Window

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

211

Page 5

Lecture notes

Digital Image Processing by Jorma Kekalainen

Workspace

Jorma Kekalainen

Digital Image Processing

212

Command History

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

213

Page 6

Lecture notes

Digital Image Processing by Jorma Kekalainen

Entering Commands
We first note that Matlab is command line driven; all
commands are entered by typing them after the
prompt symbol.
Let's start with a mathematical classic: first pressing
1+2
>> 1+2
and then press your Enter key.
This sends the command to the Matlab kernel.
What you should now see is
ans =
3
Jorma Kekalainen

Digital Image Processing

214

Matlab as a calculator
Matlab can be used as a calculator; it understands the standard
arithmetic operations of addition, subtraction, multiplication,
division and exponentiation.
Try these:
>> 4*5
>> 6-3
>> 13/7
>> 2^5
Note that for the output of 13/7 the result was only given to a few
decimal places ( 1.8571)
In fact Matlab does all its calculations internally to double precision.
However, the default display format is to use only few decimal
places.
We can change this by using the format function.
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

215

Page 7

Lecture notes

Digital Image Processing by Jorma Kekalainen

Display format
For example:
>> format long
>> 13/7
ans=
1.857142857142857
Entering the command format by itself returns to the default
format.
>> format
>> 13/7
ans =
1.8571
Jorma Kekalainen

Digital Image Processing

216

Elementary mathematical
functions
Matlab has all the elementary mathematical functions built in:
>> sqrt(2)
ans =
1.4142
The trigonometric functions all
>> sin(pi/8)
ans =
take radian arguments; and pi is a
0.3827
built-in constant.
>> log(10)
ans =
The functions
2.3026
log and log10 are the natural
>> log10(2)
logarithm and logarithms to base
ans =
10.
0.3010
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

217

Page 8

Lecture notes

Digital Image Processing by Jorma Kekalainen

Variables
When using any sort of computer system, we need to
store things with appropriate names.
In the context of Matlab, we use variables to store
values.
Here are some examples:
>> a=5^(7/2)
a=
279.5085
>> b=sin(pi/9)-cos(pi/9)
b=
-0.5977
Jorma Kekalainen

Digital Image Processing

218

Note
Note that although a and b are displayed
using the short format, Matlab in fact stores
their full values.
We can see this with:
>> format long;a,format
a=
2.795084971874737e+02

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

219

Page 9

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
We can now use these new variables in
further calculations:
>> log(a^2)/log(5)
ans =
7
>> atan(1/b)
ans =
-1.0321
Jorma Kekalainen

Digital Image Processing

220

Working with desktop


As we work in MATLAB, we write commands that
create variables and call functions.
For example, create a variable named a by typing
this statement at the command line:
>>a = 1
MATLAB adds variable a to the workspace and
displays the result in the Command Window.
a=
1
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

221

Page 10

Lecture notes

Digital Image Processing by Jorma Kekalainen

Working with desktop

Create a few more variables:


>>b = 2
b=
2
>>c = a + b
c=
3
>>d = cos(a)
d=
0.5403
When you do not specify an output variable, MATLAB uses the variable ans, short
for answer, to store the results of your calculation.
>>sin(a)
ans =
0.8415

Jorma Kekalainen

Digital Image Processing

222

Working with desktop


If you end a statement with a semicolon, MATLAB
performs the computation, but suppresses the
display of output in the Command Window.
e = a*b;
You can recall previous commands by pressing
the up- and down-arrow keys, and .
Press the arrow keys either at an empty
command line or after you type the first few
characters of a command.
For example, to recall the command b = 2, type b,
and then press the up-arrow key.
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

223

Page 11

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
Simplest way to achieve
some printing on the screen
is to leave out the semicolon used to end rows.
Function disp works in the
same manner with the
exception that it does not
print the variable names

Jorma Kekalainen

>> A=rand(3);
>> A
A=
0.4218 0.9595
0.9157 0.6557
0.7922 0.0357
>> disp(A)
0.4218 0.9595
0.9157 0.6557
0.7922 0.0357

0.8491
0.9340
0.6787
0.8491
0.9340
0.6787

Digital Image Processing

224

Workspace
The workspace contains variables that you create within or
import into MATLAB from data files or other programs.
Workspace lists all your currently defined variables, their
numeric data types, and their sizes in bytes.
The same information can be obtained using the whos
function:
>>whos
Name Size
a
1x1
ans 1x1
b
1x1
c
1x1
d
1x1
e
1x1
Jorma Kekalainen

Lecture weeks 5 and 6

Bytes
8
8
8
8
8
8

Class Attributes
double
double
double
double
double
double
Digital Image
Processing

225

Page 12

Lecture notes

Digital Image Processing by Jorma Kekalainen

who
A listing of the variable names only is obtained
using who:
>> who
Your variables are:
a ans b
c
d
e
The numeric data type double is Matlab's
standard for numbers; such numbers are
stored as doubleprecision 8-byte values.
Note also that ans is variable: it is automatically created by Matlab to store the result
Jorma Kekalainen
Digital Image Processing
226
of the
last calculation.

Complex numbers
Complex numbers have both real and imaginary
parts, where the imaginary unit is the square
root of 1.
sqrt(-1)
To represent the imaginary part of complex
numbers, use either i or j.
c = [3+4i, 4+3j, -i, 10j]

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

227

Page 13

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
>> clear
>> sqrt(-1)
ans =
0.0000 + 1.0000i
>> c = [3+4i, 4+3j, -i, 10j]
c=
3.0000 + 4.0000i 4.0000 + 3.0000i 0.0000 - 1.0000i 0.0000 +10.0000i

Jorma Kekalainen

Digital Image Processing

228

Example
>> whos
Name Size
ans
c

Jorma Kekalainen

Lecture weeks 5 and 6

1x1
1x4

Bytes Class

Attributes

16 double complex
64 double complex

Digital Image Processing

229

Page 14

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
These statements create variables A and B in the
workspace.
clear
A = magic(4);
B = rand(3,5,2);
You can view the contents of the workspace using
whos.
>>whos
Name
Size
Bytes Class Attributes
A
4x4
128 double
B
3x5x2
240 double
Jorma Kekalainen

Digital Image Processing

230

Example
>> B = rand(3,5,2)

>> A = magic(4)

B(:,:,1) =

A=
16 2 3
5 11 10
9 7 6
4 14 15

13
8
12
1

0.7060 0.0462 0.6948 0.0344 0.7655


0.0318 0.0971 0.3171 0.4387 0.7952
0.2769 0.8235 0.9502 0.3816 0.1869

B(:,:,2) =
0.4898 0.7094 0.6797 0.1190 0.3404
0.4456 0.7547 0.6551 0.4984 0.5853
0.6463 0.2760 0.1626 0.9597 0.2238

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

231

Page 15

Lecture notes

Digital Image Processing by Jorma Kekalainen

Workspace pane
The variables also appear in the Workspace
pane on the desktop.

Jorma Kekalainen

Digital Image Processing

232

Saving and restoring data


Workspace variables do not persist after you exit MATLAB.
Save your data for later use with the save command,
save myfile.mat
Saving preserves the workspace in your current working
folder in a compressed file with a .mat extension, called a
MAT-file.
To clear all the variables from the workspace, use the clear
command.
Restore data from a MAT-file into the workspace using
load.
load myfile.mat

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

233

Page 16

Lecture notes

Digital Image Processing by Jorma Kekalainen

Digital Image Processing


Arrays and matrices in
Matlab

Matrices and arrays


Matlab is an abbreviation for Matrix laboratory."
While other programming languages mostly work
with numbers one at a time, Matlab is designed
to operate primarily on whole matrices and
arrays.
All Matlab variables are multidimensional arrays,
no matter what type of data.
A matrix is a two dimensional array often used for
linear algebra.
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

235

Page 17

Lecture notes

Digital Image Processing by Jorma Kekalainen

Matrix
Matrix is an array of numbers consisting of horizontal rows
and vertical columns
Individual numbers in matrix are called elements: for example
element aij refers to the matrix element in row i and column j.
Matrices consisting of only one row or column are called row
or column vectors accordingly.

Jorma Kekalainen

Digital Image Processing

236

Array creation
To create an array with four elements in a
single row, separate the elements with either
a comma (,) or a space.
A = [1 2 3 4] or A = [1,2,3,4]
returns
A=
1234
This type of array is a row vector.
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

237

Page 18

Lecture notes

Digital Image Processing by Jorma Kekalainen

Creating vectors
1st way:
a = 3 5 7 -2 8 13
a = [3 5 7 -2 8 13]
2nd way: vector = first value : step : last value
a = 0:6
a =0 1 2 3 4 5
b = 1:3:14
b =1 4 7 10 13
c = 5:-1:0
c =5 4 3 2 1 0
3rd way:
vector = linspace(minimum value, maximum value,
number of elements)
a = linspace(1, 3, 6) a =1.0000 1.4000 1.8000 2.2000 2.6000
b=linspace(1, 3, 5)

3.0000

b =1.0000 1.5000 2.0000 2.5000 3.0000


Jorma Kekalainen

Digital Image Processing

238

Array creation
To create a matrix that has multiple rows,
separate the rows with semicolons.
>>A= [1 2 3; 4 5 6; 7 8 10]
A=
1
2
3
4
5
6
7
8
10
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

239

Page 19

Lecture notes

Digital Image Processing by Jorma Kekalainen

Array creation
Another way to create a matrix is to use a function, such as
ones, zeros, or rand.
For example, create a 5-by-1 column vector of zeros, 1-by-5
row vector of ones and a 5-by-5 identity matrix with ones on
the main diagonal and elsewhere zeros
>>x = zeros(5,1), y=ones(1,5), z=eye(5)
x=
z=
0
1 0 0 0 0
0
0 1 0 0 0
0
0 0 1 0 0
0
0 0 0 1 0
0
0 0 0 0 1
y=
1
Jorma Kekalainen

1
Digital Image Processing

240

Array indexing
Every variable in Matlab is an array that can hold many
numbers.
When you want to access selected elements of an
array, use indexing.
For example, consider the 4-by-4 magic square M:
>>M= magic(4)
M=
16
2
3
13
5
11
10
8
9
7
6
12
4
14
15
1
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

241

Page 20

Lecture notes

Digital Image Processing by Jorma Kekalainen

Array indexing
There are two ways to refer to a particular
element in an array.
The most common way is to specify row and
column subscripts, such as
>>M(4,2)
ans =
M=
14
16 2 3
5 11 10
9 7 6
4 14 15
Jorma Kekalainen

Digital Image Processing

13
8
12
1
242

Linear indexing
Less common, but sometimes useful, is to use
a single subscript that traverses down each
column in order:
M=
>>M(8)
16 2 3 13
5 11 10 8
ans =
9 7 6 12
4 14 15 1
14
Using a single subscript to refer to a particular
element in an array is called linear indexing.
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

243

Page 21

Lecture notes

Digital Image Processing by Jorma Kekalainen

Note

If you try to refer to elements outside an array on the right side of an


assignment statement, MATLAB throws an error.
>>test = M(4,5)
Attempted to access M(4,5); index out of bounds because size(M)=[4,4].
However, on the left side of an assignment statement, you can specify
elements outside the current dimensions.
The size of the array increases to accommodate the newcomers
>>M(4,5) = 17
M=
16
2
3
13
0
5
11
10
8
0
9
7
6
12
0
4
14
15
1
17

Jorma Kekalainen

Digital Image Processing

244

Referring to multiple elements


To refer to multiple elements of an array, use the
colon operator, which allows you to specify a
range of the form start:end.
For example, list the elements in the first three
rows in the second column of M:
>>M(1:3,2)
ans =
M=
2
11
16 2 3 13 0
5 11 10 8 0
7
9 7 6 12 0
4 14 15
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

1 17
245

Page 22

Lecture notes

Digital Image Processing by Jorma Kekalainen

Referring to multiple elements


The colon alone, without start or end values,
specifies all of the elements in that dimension.
For example, select all the columns in the third
row of M:
M=

>>M(3,:)

16 2 3 13 0
5 11 10 8 0
9 7 6 12 0
4 14 15 1 17

ans =
9
Jorma Kekalainen

12

Digital Image Processing

246

Referring to multiple elements


The colon operator also allows you to create an
equally spaced vector of values using the more
general form start:step:end.
>>B = 0:10:100
B=
0 10 20 30 40 50 60 70 80 90 100
If you omit the middle step, as in start:end, Matlab
uses the default step value of 1
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

247

Page 23

Lecture notes

Digital Image Processing by Jorma Kekalainen

Entering a matrix
Matlab has a large number of commands for generating and
manipulating matrices.
Since a grayscale image is an matrix, we can use some of
those commands to investigate aspects of the image.
We can enter a small matrix by listing its elements row by row,
using spaces or commas as delimiters for the elements in each
row, and using semicolons to separate the rows.
Thus the matrix

can be entered as
>> a=[4 -2 -4 7;1 5 -3 2;6 -8 -5 -6;-7 3 0 1]
Jorma Kekalainen

Digital Image Processing

248

Matrix elements
Matrix elements can be obtained by using the
standard row, column indexing scheme.
So for our image matrix a above, the command
>> a(2,3)
ans =
-3
returns the element of the matrix in row 2 and
column 3.
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

249

Page 24

Lecture notes

Digital Image Processing by Jorma Kekalainen

Matrix elements
Matlab also allows matrix elements to be obtained using a
single number; this number being the position when the
matrix is written out as a single column.
Thus in a (4*4) matrix as above, the order of elements is

So the element a(2,3) can also be obtained as a(10):


>> a(10)
ans =
-3
Jorma Kekalainen

Digital Image Processing

250

Colon operator (:)


To obtain a row of values, or a block of values, we
use Matlab's colon operator (:).
This generates a vector of values; the command
a:b
where a and b are integers, lists all integers from a to
b.
The more general version of this command:
a:i:b
lists all values from a by increment i up to b.
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

251

Page 25

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
So for example:
>> 2:3:16
generates the list
ans =
2 5 8 11 14
Applied to our matrix a, for example:
>> a(3,1:3)
ans =
6 -8 -5
lists all values in row 3 which are between columns 1 and 3
inclusive.
Jorma Kekalainen

Digital Image Processing

252

Example
Similarly
>> a(2:4,3)
ans =
-3
-5
0
lists all the values in column 3 which are between rows 2 to 4
inclusive.
We can choose a block of values such as
>> a(2:3,3:4)
ans =
-3 2
-5 -6
which lists the 2 by 2 block of values which lie between rows 2 to 3
and columns 3 to 4.
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

253

Page 26

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
The colon operator by itself lists all the elements along that
particular row or column.
So, for example, all of row 3 can be obtained with:
>> a(3,:)
ans =
6 -8 -5 -6
and all of column 2 with
>> a(:,2)
ans =
-2
5
-8
3

>> a(:)
ans =
4
1
6
-7
-2
5
-8
3
-4
-3
-5
0
7
2
-6
1

Note: Finally, the colon on its own lists all the matrix elements as a single column: a(:)
Jorma Kekalainen
Digital Image Processing
254
shows all the 16 elements of a.

Matrix operations
All the standard operations are supported.
We can add, subtract, multiply and invert matrices, and take matrix
powers.
For example, with the matrix a from above, and a new matrix b
defined by
>> b=[2 4 -7 -4;5 6 3 -2;1 -8 -5 -3;0 -6 7 -1]
we can have, for example:
>> 2*a-3*b
ans =
2 -16 13 26
-13 -8 -15 10
9 8 5 -3
-14 24 -21 1
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

255

Page 27

Lecture notes

Digital Image Processing by Jorma Kekalainen

Matrix product
The product of matrixes A and B is defined
only if the following holds for matrix
dimensions (dim)
dim A = n x p, dim B = p x k, dim C = n x k

Jorma Kekalainen

>> A=[1:3;4:6];
>> B=[1
2;-1 -1;-2 0];
Digital Image Processing
>> C=A*B

256

Example
>> A=[1:3;4:6]
A=
1 2 3
4 5 6
>> B=[1 2;-1 -1;-2 0]
B=
1 2
-1 -1
-2 0
>> C=A*B
C=
-7 0
-13 3

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

257

Page 28

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
As an example of matrix powers:
>> a^3*b^4
ans =

Inversion is performed using the inv function:


>> inv(a)
ans =

Jorma Kekalainen

Digital Image Processing

258

Transpose
A transpose is obtained by using the
apostrophe:
>> a'
ans =
4 1 6 -7
-2 5 -8 3
-4 -3 -5 0
7 2 -6 1
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

259

Page 29

Lecture notes

Digital Image Processing by Jorma Kekalainen

Geometric operations on matrices


As well as these standard arithmetic operations, Matlab
supports some geometric operations on matrices; flipud and
fliplr flip a matrix up/down and left/right respectively, and
rot90 rotates a matrix by 90 degrees:
>> flipud(a)
ans =

>> fliplr(a)
ans =
Jorma Kekalainen

Digital Image Processing

260

Geometric operations on matrices


>> rot90(a)
ans =

Jorma Kekalainen

Lecture weeks 5 and 6

90

Digital Image Processing

261

Page 30

Lecture notes

Digital Image Processing by Jorma Kekalainen

Matrix and array operations


Matlab allows to process all of the values in a matrix using a
single arithmetic operator or function.
>>A + 10
A= [1 2 3; 4 5 6; 7 8 10]
ans =
A=
11
12
13
1
2
14
15
16
4
5
7
8
17
18
20
>>sin(A)
ans =
0.8415
0.9093
0.1411
-0.7568
-0.9589
-0.2794
0.6570
0.9894
-0.5440
Jorma Kekalainen

Digital Image Processing

3
6
10

262

Matrix and array operations


To transpose a matrix, use a single quote ('):
>>A'
ans =
1
4
7
2
5
8
3
6
10
A=

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

1
4
7

2 3
5 6
263
8 10

Page 31

Lecture notes

Digital Image Processing by Jorma Kekalainen

Matrix and array operations


We can perform standard matrix multiplication,
which computes the inner products between
rows and columns, using the * operator.
For example, confirm that a matrix times its
inverse returns the identity matrix:
>>p = A*inv(A)
p=
1.0000
0
-0.0000
0
1.0000
0
0
0
1.0000
Jorma Kekalainen

Digital Image Processing

264

Note

Notice that p is not a matrix of integer values.


Matlab stores numbers as floating-point values, and arithmetic operations
are sensitive to small differences between the actual value and its
floating-point representation.
We can display more decimal digits using the format command:
>>format long
>>p = a*inv(a)
p=
1.000000000000000
0
-0.000000000000000
0
1.000000000000000
0
0
0
0.999999999999998
Reset the display to the shorter format using
format short
format affects only the display of numbers, not the way Matlab computes
or saves them.

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

265

Page 32

Lecture notes

Digital Image Processing by Jorma Kekalainen

Note
All these commands work equally well on
vectors.
In fact, Matlab makes no distinction between
matrices and vectors; a vector merely being a
matrix with number of rows or columns equal
to 1.

Jorma Kekalainen

Digital Image Processing

266

Dot operators
A very distinctive class of operators in Matlab are those
which use dots; these operate in an element-wise
fashion element-wise operations.
For example, the command
a*b
performs the usual matrix multiplication of a and b.
But the corresponding dot operator:
a.*b
produces the matrix whose elements are the products
of the corresponding elements of a and b.
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

267

Page 33

Lecture notes

Digital Image Processing by Jorma Kekalainen

Dot product
That is, if
a.*b
then the element of dot product is c(i,j)=
a(i,j)*b(i,j)
b=[2 4 -7 -4;5 6 3 -2;1 -8 -5 -3;0 -6 7 -1]
b=
>> a.*b
2 4 -7 -4
5 6 3 -2
ans =
1 -8 -5 -3
0 -6

Jorma Kekalainen
Digital Image Processing
Note:
We have also dot division,
and dot powers.

7 -1

268

Example
The command a.^2 produces a matrix each
element of which is a square of the
corresponding elements of a:
>> a.^2
ans =

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

269

Page 34

Lecture notes

Digital Image Processing by Jorma Kekalainen

Matrix of reciprocals
Similarly, we can produce a matrix of
reciprocals by writing 1./a:
>> 1./a
ans =

Note: The value Inf is Matlab's version of infinity; Here it is returned for
Kekalainen
Digital Image Processing
270
the Jorma
operation
1/0.

Example: Element-wise operations

To perform element-wise multiplication rather than matrix multiplication,


use the .* operator:
A=[1:3;4:6;7 8 10]
>>p = A.*A
p=
A=
1
4
9
16
25
36
1 2 3
49
64
100
4 5 6
The matrix operators for multiplication, division, and power each have7 a 8 10
corresponding array operator that operates element-wise.
For example, raise each element of a to the third power:
>>A.^3
ans =
1
8
27
64
125
216
A=
343
512
1000

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

1
4
7

2 3
5 6
271
8 10

Page 35

Lecture notes

Digital Image Processing by Jorma Kekalainen

Concatenation
Concatenation is the process of joining arrays to
make larger ones.
The pair of square brackets [] is the
concatenation operator.
C = [A,A]
Horizontal concatenation
C=
1
2
3
1
2
3
4
5
6
4
5
6
A=
7
8
10 7
8
10
Jorma Kekalainen

Digital Image Processing

1
4
7

2 3
5 6
272
8 10

Concatenation
Concatenating arrays next to one another using commas is called
horizontal concatenation.
Each array must have the same number of rows.
Similarly, when the arrays have the same number of columns, you
can concatenate vertically using semicolons.
C= [A; A]
Vertical concatenation
C=
1
2
3
4
5
6
7
8
10
1
2
3
4
5
6
7
8
10
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

273

Page 36

Lecture notes

Digital Image Processing by Jorma Kekalainen

Constructing matrices
We have seen that we can construct matrices by listing all their
elements.
However, this can be tedious if the matrix is large.
Two special matrices are the matrix consisting of all zeros, and the
matrix consisting of all ones.
These are generated by the zeros and ones functions respectively.
Each function can be used in several different ways:
zeros(n) if n is a number, will produce a zeros matrix of size (n*n)
zeros(m,n) if m and n are numbers, will produce a zeros matrix of size (m*n)
zeros(m,n,p,...) where m, n, p and so on are numbers, will produce an
m*n*p* multidimensional array of zeros
zeros(a) where a is a matrix, will produce a matrix of zeros of the same size
as a.

Jorma Kekalainen

Digital Image Processing

274

Example

Jorma Kekalainen

Lecture weeks 5 and 6

>> zeros(3)
ans =
0 0 0
0 0 0
0 0 0
>> zeros(3,4)
ans =
0 0 0 0
0 0 0 0
0 0 0 0
>> zeros(1,2)
ans =
0Digital Image
0 Processing

275

Page 37

Lecture notes

Digital Image Processing by Jorma Kekalainen

eye
Command eye creates an identity matrix
>> eye(3)
ans =
1 0 0
0 1 0
0 0 1
>> eye(3,4)
ans =
1 0 0
0 1 0
0 0 1
Jorma Kekalainen

0
0
0

Digital Image Processing

276

Matrices of random numbers


Matrices of random numbers can be produced using
the rand and randn functions.
They differ in that the numbers produced by rand are
taken from a uniform distribution on the interval [0,1],
and those produced by randn are take from a normal
distribution with mean zero and standard deviation
one.
For creating matrices the syntax of each is the same as
the first three options of zeros above.
The rand and randn functions on their own produce
single numbers taken from the appropriate
distribution.
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

277

Page 38

Lecture notes

Digital Image Processing by Jorma Kekalainen

Random integer matrices


We can construct random integer matrices by multiplying the
results of rand or randn by an integer and then using the floor
function to take the integer part of the result:
>> floor(10*rand(3))
The floor function will be automatically
applied to every element in the matrix.
ans =
8 4 6
8 8 8
5 8 6
>> floor(100*randn(3,5))
ans =
Jorma Kekalainen

Digital Image Processing

278

Example
Suppose we wish to create a matrix every
element of which is a function of one of its
indices.
For example, the (5*5) matrix A for which
Aij=i+j-1.
In most programming languages, such a task
would be performed using nested loops.
We can use nested loops in Matlab, but it is
easier here to use dot operators.
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

279

Page 39

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
We can first construct two matrices: one containing all the
row indices, and one containing all the column indices:
>> rows=(1:5)'*ones(1,5)
rows =
>> cols=ones(5,1)*(1:5)
11111
cols =
22222
12345
33333
12345
12345
44444
12345
55555
12345

Jorma Kekalainen

Digital Image Processing

280

Example
Now we can construct our matrix using rows and cols:
>> [cols,rows]=meshgrid(1:5,1:5)
>> A=rows+cols-1
cols =
A=
1 2 3 4 5
1 2 3 4 5
12345
1 2 3 4 5
23456
1 2 3 4 5
1 2 3 4 5
34567
rows =
1 1 1 1 1
45678
2 2 2 2 2
56789
3 3 3 3 3
4
5

4
5

4
5

4
5

4
5

Note: The construction of rows and cols can be done automatically with the meshgrid
function:
[cols,rows]=meshgrid(1:5,1:5)
Jorma Kekalainen
Image Processing
281
will produce
the two index matrices Digital
above.

Lecture weeks 5 and 6

Page 40

Lecture notes

Digital Image Processing by Jorma Kekalainen

Size of the matrix


The size of our matrix a can be obtained by
using the size function:
size(a)
which returns the number of rows and
columns of a.
>>size(A)
ans =
5
5
Jorma Kekalainen

Digital Image Processing

282

Note
Many functions in Matlab, when applied to a
matrix, work by applying the function to each
element in turn.
Such functions are the trigonometric and
exponential functions, and logarithms.
The use of functions in this way means that in
Matlab many iterations and repetitions can be
done with vectorization rather than by using
loops.
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

283

Page 41

Lecture notes

Digital Image Processing by Jorma Kekalainen

Vectorization
Vectorization, in Matlab, refers to an operation
carried out over an entire matrix or vector.
In most programming languages, applying an
operation to elements of a list or array will
require the use of a loop, or a sequence of nested
loops.
Vectorization in Matlab allows us to do without
loops in almost all instances, and is a very
efficient replacement for them.
Jorma Kekalainen

Digital Image Processing

284

Example
Suppose we wish to calculate the cosine values of all the
integer radians one to ten million.
We can do this with a for-loop:
for i=1:10^7,cos(i);end
We can measure the time of the operation with Matlab's tic,
toc timer: tic starts a stop watch timer, and toc stops it and
prints out the elapsed time in seconds.
Thus, on this computer:
>> tic,for i=1:10^7,cos(i);end,toc
Elapsed time is 5.836959 seconds.

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

285

Page 42

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
We can perform the same calculation with:
>> i=1:10^7;cos(i);
and print out the elapsed time with:
>> tic,i=1:10^7;cos(i);toc
Elapsed time is 1.311342 seconds.
Note that the second command applies the
cosine function to all the elements of the vector
1:10^7, whereas with the for loop, cosine is only
applied to each element of the loop in turn.
Jorma Kekalainen

Digital Image Processing

286

Example
As another example, we can easily generate
the first 10 square numbers with:
>> [1:10].^2
ans =
1 4 9 16 25 36 49 64 81 100
What happens here is that [1:10] generates a
vector consisting of the numbers 1 to 10; and
the dot operator .^2 squares each element in
turn.
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

287

Page 43

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
Vectorization can also be used with logical operators;
we can obtain all positive elements of the matrix a
above with:
>> a>0
ans =
1 0 0 1
1 1 0 1
1 0 0 0
0 1 0 1
The result consists of 1's only in the places where the
elements are positive.
Note: Matlab is designed to perform vectorized commands very quickly, and whenever
Jorma Kekalainen
Processing
288
possible
such a command should be Digital
usedImage
instead
of a for loop.

Digital Image Processing


2-D and 3-D Plots in
Matlab

Lecture weeks 5 and 6

Page 44

Lecture notes

Digital Image Processing by Jorma Kekalainen

Basic commands

Jorma Kekalainen

Digital Image Processing

290

Title and labels


Figure header can be added by using
command title
Axis explanations can be added by typing
xlabel, ylabel and zlabel
Line comments are added with command
legend
Construction lines are shown by typing grid on
Scale of the axes can be altered using
command axis
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

291

Page 45

Lecture notes

Digital Image Processing by Jorma Kekalainen

Line plots
The idea is straightforward: we create two
vectors x and y of the same size, then the
command
plot(x,y)
will draw two-dimensional line plot y against
x.
If y has been created from x by using a
vectorized function f(x) the plot will show the
graph of y=f(x)
Jorma Kekalainen

Digital Image Processing

292

Example
x=[0:0.1:2*pi];
plot(x,sin(x))
and the result is shown
beside.

Jorma Kekalainen

Lecture weeks 5 and 6

A simple plot

Digital Image Processing

293

Page 46

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
The plot function can be used
to produce many different
plots.
We can, e.g., plot two
functions simultaneously with
different colors or plot
symbols.
For example:
plot(x,sin(x),'o',x,cos(x),'*')
produces the graph shown
beside.
Jorma Kekalainen

Digital Image Processing

294

Example
Plot the value of the cosine function from 0 to
2:
x = 0:pi/100:2*pi;
y = cos(x);
plot(x,y)

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

295

Page 47

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
We can label the axes and add a title.
title('Plot of the Cosine Function')
xlabel('x')
ylabel('cos(x)')

Jorma Kekalainen

Digital Image Processing

296

Example
By adding a third
input argument to
the plot function,
you can plot the
same variables using
a red dashed line.
plot(x,y,'r--')

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

297

Page 48

Lecture notes

Digital Image Processing by Jorma Kekalainen

Line specification
The 'r--' string is a line specification.
Each specification can include characters for the line
color, style, and marker.
A marker is a symbol that appears at each plotted
data point, such as a +, o, or *.
For example, 'g:*' requests a dotted green line with *
markers.
plot(x,y,'g:*' )

Jorma Kekalainen

Digital Image Processing

298

Note
Notice that the titles and labels that you
defined for the first plot are no longer in the
current figure window.
By default, Matlab clears the figure each time
you call a plotting function, resetting the axes
and other elements to prepare the new plot.

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

299

Page 49

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
To add plots to an existing figure, use hold.
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
hold on
y2 = cos(x);
plot(x,y2,'r:')
legend('sin','cos')
Until you use hold off or close the window, all plots appear
in the current figure window.
Jorma Kekalainen

Digital Image Processing

300

Note

It is possible to combine Greek alphabet to figures as well as sub-and


superscripts.

t = 0:0.1:500; y = sin(100.*t*10^-3).*exp(-8.*t*10^-3);
figure,plot(t, y);
title('{\itAe}^{-\alpha\itt}sin\beta{\itt} \alpha<<\beta');
xlabel('Time \musec.');
ylabel('Amplitude');

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

301

Page 50

Lecture notes

Digital Image Processing by Jorma Kekalainen

Note
Explanation for the title:

Subscripts are added by using underline character


( _ ): For example, A0 is given in form A_0
Jorma Kekalainen

Digital Image Processing

302

Example
Basic command: plot

First parameter: values in the x-axis


Second parameter: values in the y-axis
Additional parameters to customize the line type
and colors.
t = (0:0.1:10)';
y = sin(2*pi*0.2*t);
figure
plot(t,y,'r+')

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

303

Page 51

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
t = (0:0.1:10)';
y = sin(2*pi*0.2*t);
figure
plot(t,y,'r+')
hold on
line([0 10],[0 0])
xlabel('Time (s)')
ylabel('\it{sin(2\pift)}')
title('Graph')
grid on
Jorma Kekalainen

Digital Image Processing

304

Subplots
We can display multiple plots in different subregions of the
same window using the subplot function.
For example, create three plots in a 3-by-1 grid within a figure
window. The first two inputs to the subplot function indicate the number
of plots in each row and column. The third input specifies which
plot is active.
t=-3*pi:0.01:3*pi;
yb=cos(t)-(1/3)*cos(3*t)+(1/5)*cos(5*t);
yc=cos(t)-0.5*(1/3)*cos(3*t);
yd=cos(t)-2*(1/3)*cos(3*t);
subplot(311),plot(t,yb),grid
title('yb=cos(t)-(1/3)*cos(3*t)+(1/5)*cos(5*t)')
subplot(312),plot(t,yc),grid
title('yc=cos(t)-0.5*(1/3)*cos(3*t)')
subplot(313),plot(t,yd),grid
Jorma Kekalainen
Digital Image Processing
title('yd=cos(t)-2*(1/3)*cos(3*t)')

Lecture weeks 5 and 6

305

Page 52

Lecture notes

Digital Image Processing by Jorma Kekalainen

3-D plots
Three-dimensional plots typically display a
surface defined by a function in two variables,
z = f (x,y).
To evaluate z, first create a set of (x,y) points
over the domain of the function using
meshgrid.
[X,Y] = meshgrid(-2:.2:2);
Z = X .* exp(-X.^2 - Y.^2);
Jorma Kekalainen

Digital Image Processing

306

3-D plots
Then, create a surface plot.
surf(X,Y,Z)

Jorma Kekalainen

Lecture weeks 5 and 6

Both the surf function and its


companion mesh display surfaces in
three dimensions.
surf displays both the connecting
lines and the faces of the surface
in color.
mesh produces wireframe surfaces
that color only the lines connecting
the defining points.

Digital Image Processing

307

Page 53

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
Generate a cylinder defined
by the profile function
2+sin(t).
t = 0:pi/10:2*pi;
[X,Y,Z] = cylinder(2+cos(t));
surf(X,Y,Z)
axis square

Jorma Kekalainen

Digital Image Processing

308

Subplots
We can display multiple plots in different subregions of the
same window using the subplot function.
For example, create four plots in a 2-by-2 grid within a
figure window.
t = 0:pi/10:2*pi;
[X,Y,Z] = cylinder(4*cos(t));
subplot(2,2,1); mesh(X); title('X');
subplot(2,2,2); mesh(Y); title('Y');
subplot(2,2,3); mesh(Z); title('Z');
subplot(2,2,4); mesh(X,Y,Z); title('X,Y,Z');

The first two inputs to the subplot function indicate the


number of plots in each row and column.
The third input specifies which plot is active.
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

309

Page 54

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example: Subplots

Jorma Kekalainen

Digital Image Processing

310

Digital Image Processing


Character Strings in
Matlab

Lecture weeks 5 and 6

Page 55

Lecture notes

Digital Image Processing by Jorma Kekalainen

Character strings
A character string is a sequence of any number of
characters enclosed in single quotes.
You can assign a string to a variable.
>> myText = 'Hi, neighbor';
If the text includes a single quote, use two single
quotes within the definition.
>> otherText = 'You''re right!'
otherText =
You're right!
Jorma Kekalainen

Digital Image Processing

312

Class char
myText and otherText are arrays, like all Matlab variables.
Their class or data type is char, which is short for character.
>> whos myText
Name
Size
Bytes Class Attributes
myText

1x12

24 char

>> whos otherText


Name
Size
Bytes Class Attributes
otherText
Jorma Kekalainen

Lecture weeks 5 and 6

1x13

26 char
Digital Image Processing

313

Page 56

Lecture notes

Digital Image Processing by Jorma Kekalainen

Concatenating strings
You can concatenate strings with square brackets, just as you
concatenate numeric arrays.
>> longText = [myText,' - ',otherText]
longText =
Hi, neighbor - You're right!
>> whos
Name
Size
longText
myText
otherText

1x28
1x12
1x13

Jorma Kekalainen

Bytes Class Attributes


56 char
24 char
26 char
Digital Image Processing

314

Converting numeric values to


strings
To convert numeric values to strings, use functions, such as
num2str or int2str.
>> f = 69;
>>c = (f-32)/1.8;
>>tempText = ['Temperature is ',num2str(c), ' degrees
Celsius']
tempText =
Temperature is 20.5556 degrees Celsius

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

315

Page 57

Lecture notes

Digital Image Processing by Jorma Kekalainen

whos
>> whos
Name

Size

c
f
longText
myText
otherText
tempText
Jorma Kekalainen

Bytes Class

1x1
1x1
1x28
1x12
1x13
1x38

8
8
56
24
26
76

Attributes

double
double
char
char
char
char

Digital Image Processing

316

Interactivity: input
User can be asked for input,
The question to be asked from the user is given as a
parameter to the input-function
The input function returns the answer of the user.
age = input('How old are you?\n');
note the line feed (\n) in the question to obtain question and
answer on different rows
>> age = input('How old are you?\n');
How old are you?
20

Jorma Kekalainen

Lecture weeks 5 and 6

>> age = input('How old are you?');


How old are you?20

Digital Image Processing

317

Page 58

Lecture notes

Digital Image Processing by Jorma Kekalainen

Interactivity: input
Use parameter 's' to express that you want the return value to
be of type character string.
type = input('Low or high pass filter?\n', 's');
>> type = input('low or high pass filter?\n', 's');
low or high pass filter?
low
>> type
type =
low
>> type=input('Give the filter type: Low pass = ''low'' and High pass = ''high''\n', 's');
Give the filter type: Low pass = 'low' and High pass = 'high'
high
>> type
type =
Jorma
Digital Image Processing
318
highKekalainen

Digital Image Processing


Programming and Scripts
in Matlab

Lecture weeks 5 and 6

Page 59

Lecture notes

Digital Image Processing by Jorma Kekalainen

Introduction
Matlab was first used by entering simple commands
from the command line
This is not practical when implementing complex things
requiring tens of commands or multiple repetitions of
the same task.
Reasons for this impracticality are:
errors are easily made
all the commands have to be entered once again when
detecting an error in the beginning of the command series
entering commands by hand is very slow
there will be no documentation of the entered commands

Programming solves this problem.


Jorma Kekalainen

Digital Image Processing

320

Script
The simplest type of Matlab program is called
a script.
A script is a file with a .m extension that
contains multiple sequential lines of Matlab
commands and function calls.
We can run a script by typing its name at the
command line (without .m extension).

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

321

Page 60

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
To create a script, use the edit command, e.g.,
edit plotrand
This opens a blank file named plotrand.m.
Enter some code that plots a vector of random data:
n = 50;
r = rand(n,1);
plot(r)
Next, add code that draws a horizontal line on the plot at the mean:
m = mean(r);
hold on
plot([0,n],[m,m])
hold off
title('Mean of Random Uniform Data')
Note: Whenever we write code, it is a good practice to add comments that describe
the code. Comments allow others to understand our code, and can refresh our
Jorma Kekalainen
Digital Image Processing
memory
when we return to it later. Add
comments using the percent (%) symbol.322

Editor Window
>> edit plotrand1

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

323

Page 61

Lecture notes

Digital Image Processing by Jorma Kekalainen

Creating a script

>> edit plotrand1

Jorma Kekalainen

Digital Image Processing

324

Example: Plotrand1
% Generate random data from a uniform distribution
% and calculate the mean. Plot the data and the mean.
n = 50; % 50 data points
r = rand(n,1);
plot(r)
% Draw a line from (0,m) to (n,m)
m = mean(r);
hold on
plot([0,n],[m,m])
hold off; % What happens if we start this row with %?
title('Mean of Random Uniform Data')
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

325

Page 62

Lecture notes

Digital Image Processing by Jorma Kekalainen

Saving and running script


Save the file in the current folder using save
button in Editor panel.
To run the script, type its name at the
command line:
plotrand1
You can also run scripts from the Editor by
pressing the Run button, .

Jorma Kekalainen

Digital Image Processing

326

Example: Plotrand1
% Generate random data from a uniform distribution
% and calculate the mean. Plot the data and the mean.
n = 50; % 50 data points
r = rand(n,1);
plot(r)
% Draw a line from (0,m) to (n,m)
m = mean(r);
hold on
plot([0,n],[m,m])
hold off
title('Mean of Random Uniform Data')

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

327

Page 63

Lecture notes

Digital Image Processing by Jorma Kekalainen

Branching
Its often useful to make a choice between one
or multiple alternatives
if condition
% do something
else
% do something else
if (x > y)
end
bigger = x;
else
bigger = y;
Jorma Kekalainen

Digital Image Processing

end

328

Branching
switch x
case 1
% code1
case 2
% code2
case {3, 4}
% code34
otherwise
% code
(optional
end
Jorma Kekalainen

Lecture weeks 5 and 6

x=1
x=2
x=3, x=4
otherwise

Digital Image Processing

329

Page 64

Lecture notes

Digital Image Processing by Jorma Kekalainen

Relational operators in Matlab

>> 3 < 4
ans =
1

>> 3 > 4
ans =
0

Jorma Kekalainen

Digital Image Processing

330

Example

These operators are different:


== is equal to
= is signed a value
Character strings cannot be compared using operator
==.
Use strcmp-function instead
>> 'cats' == 'dogs'
ans =
0 0 0 1
Jorma Kekalainen

Lecture weeks 5 and 6

>> strcmp('cats', 'dogs')


ans =
0
>> strcmp('cats', 'cats')
ans =
Digital Image Processing
1

331

Page 65

Lecture notes

Digital Image Processing by Jorma Kekalainen

Logical operators in Matlab

>> A = 1; B = 0;

TRUE = 1; FALSE = 0;

Jorma Kekalainen

>> A && A
ans =
1
>> A && B
ans =
0
>> TRUE & TRUE
ans =
1
>> TRUE & FALSE
ans =
Digital
0 Image Processing

>> A || B
ans =
1
>> B || B
ans =
0
>> TRUE | FALSE
ans =
1
>> TRUE|TRUE
ans =
1

332

for-loop
for variable = initialValue:step:finalValue
% do something
end
for index = -5:2:0
index
end

Jorma Kekalainen

Lecture weeks 5 and 6

index =
-5
index =
-3
index =
-1

Digital Image Processing

333

Page 66

Lecture notes

Digital Image Processing by Jorma Kekalainen

Examples
FOR I = 1:N,
FOR J = 1:N,
A(I,J) = 1/(I+J-1);
END
END
FOR S = 1.0: -0.1: 0.0, END
steps S with increments of -0.1
Note: The BREAK statement can be used to terminate the loop prematurely.
Jorma Kekalainen
Image Processing
See also
IF, WHILE, SWITCH, BREAK,Digital
END.

334

Example
Its possible to go through every matrix
element by using two internal for-loops
[M, N] = size(X);
total = 0;
for column = 1:N
for row = 1:M
total = total + X(row, column);
end
end

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

335

Page 67

Lecture notes

Digital Image Processing by Jorma Kekalainen

while-loop
while condition
% do something
end
element = 1;
while (element <= 10)
x(element) = element;
element = element + 1;
end
>> x
x=
1
Jorma Kekalainen

9 10

Digital Image Processing

336

for-loop vs. while-loop


for-loop is used when it is exactly known a priori how
many repetitions are to be made
e.g., going through every row and column in a matrix
number of repetitions does not necessarily have to be a
constant for instance, the size of the matrix to go through
can change from one execution to another

while-loop is used when the number of repetitions is


unknown in the beginning of the loop
e.g., the user feeds an unknown amount of numbers

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

337

Page 68

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
How much is x?
>> a = 0;
while (2)
a = a + 1;
end
>> a
a=
304383259

Process was stopped violently by control C

Jorma Kekalainen

Digital Image Processing

338

break & continue


break-command exits the loop and program
execution continues from the line after the
loop.
continue-command forces the loop to start
immediately from the beginning.

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

339

Page 69

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
index = 1;
while (index < 6)
if (index == 4)
break
end
index
index = index + 1;
end
index =
1
index =
2
index =
Jorma Kekalainen
3

index = 1;
while (index < 6)
if (index == 4)
index = index + 1;
continue
end
index
index = index + 1;
end

Digital Image Processing

index =
1
index =
2
index =
3
index =
5

340

Good practise
Program code should be easily read and
understood
easier to debug the errors
easier to remember what the code was intended for
after weeks or months
other people can more easily utilize the code in their
programs

Code is easily read when:


variables have descriptive names
indentation and empty space is used properly
it is well commented
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

341

Page 70

Lecture notes

Digital Image Processing by Jorma Kekalainen

Command string files


Matlab command string file (script, macro) is a text file
consisting of consecutive Matlab-function calls
(commands).
These files are of type *.m and they are called Matlab mfiles.
Matlab executes the commands when the name of the
command string file is written to the command line.
These files utilize the existing variables in the workspace
and store new variables created during execution to the
workspace.
These new variables can be used from the command line
after the script execution has stopped.
Jorma Kekalainen

Digital Image Processing

342

Loops and conditional statements


Within a script, you can loop over sections of code and
conditionally execute sections using the keywords for, end, while,
if, and switch.
For example, create a script named calcmean1.m that uses a for
loop to calculate the mean of five random samples and the overall
mean.
nsamples = 5;
npoints = 50;
for k = 1:nsamples
currentData = rand(npoints,1);
sampleMean(k) = mean(currentData);
end
overallMean = mean(sampleMean)

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

343

Page 71

Lecture notes

Digital Image Processing by Jorma Kekalainen

Loops and conditional statements


Now, modify the for-loop so that you can view the results at
each iteration.
Display text in the Command Window that includes the
current iteration number, and remove the semicolon from
the assignment to sampleMean.
for k = 1:nsamples
iterationString = ['Iteration #',int2str(k)];
disp(iterationString)
currentData = rand(npoints,1);
sampleMean(k) = mean(currentData)
end
overallMean = mean(sampleMean)
Jorma Kekalainen

Digital Image Processing

344

Example: Running script


>> calcmean1
Iteration #1
sampleMean =
0.5250
Iteration #2
sampleMean =
0.5250 0.5641
Iteration #3
sampleMean =
0.5250 0.5641 0.4332

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

345

Page 72

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example: Running script

Iteration #4

sampleMean =

0.5250 0.5641 0.4332 0.4950

Iteration #5

sampleMean =

0.5250 0.5641 0.4332 0.4950 0.4250

overallMean =
0.4884

Jorma Kekalainen

Digital Image Processing

346

Example: Running the script


When you run the previous calcmean1 script, it displays the
intermediate results, and then calculates the overall mean.
calcmean
Iteration #1
sampleMean =
0.3988
Iteration #2
sampleMean =
0.3988
0.4950
Iteration #3
sampleMean =
0.3988
0.4950
0.5365
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

347

Page 73

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example: Running the script


Iteration #4
sampleMean =
0.3988 0.4950 0.5365 0.4870
Iteration #5
sampleMean =
0.3988 0.4950 0.5365 0.4870 0.5501
overallMean =
0.4935

Jorma Kekalainen

Digital Image Processing

348

Editor
Type edit or edit file_name to open Matlab
editor.
It is possible to run command string files from
the command line by typing the files name.
Command string files can also be run by
pressing the run button while the editor
window is open.

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

349

Page 74

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example: Editing script


In the editor, add conditional statements to the end of
calcmean1.m that display a different message
depending on the value of overallMean.
if overallMean < .49
disp('Mean is less than expected')
elseif overallMean > .51
disp('Mean is greater than expected')
else
disp('Mean is within the expected range')
end
Jorma Kekalainen

Digital Image Processing

350

Example: Running the edited


script
Run calcmean1 and verify that the correct
message displays for the calculated
overallMean.
For example:
overallMean =
0.5178
Mean is greater than expected

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

351

Page 75

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example: Running the script


>> calcmean1
Iteration #1
sampleMean =
0.4886 0.5641 0.4332 0.4950 0.4250
Iteration #2
sampleMean =
0.4886 0.4174 0.4332 0.4950 0.4250
Iteration #3
sampleMean =
0.4886 0.4174 0.4447 0.4950 0.4250

Jorma Kekalainen

Digital Image Processing

352

Example: Running the script


Iteration #4
sampleMean =
0.4886 0.4174 0.4447 0.4977 0.4250
Iteration #5
sampleMean =
0.4886 0.4174 0.4447 0.4977 0.5112
overallMean =
0.4719
Mean is less than expected
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

353

Page 76

Lecture notes

Digital Image Processing by Jorma Kekalainen

Script locations
MATLAB looks for scripts and other files in certain
places.
To run a script, the file must be in the current
folder or in a folder on the search path.
By default, the MATLAB folder that the MATLAB
Installer creates is on the search path.
If you want to store and run programs in another
folder, add it to the search path.
Select the folder in the Current Folder browser,
right-click, and then select Add to Path.
Jorma Kekalainen

Digital Image Processing

354

Digital Image Processing


Functions in Matlab

Lecture weeks 5 and 6

Page 77

Lecture notes

Digital Image Processing by Jorma Kekalainen

Built-in functions
Matlab provides an enormous number of built-in functions
as well as the ability to define our own functions.
Functions are equivalent to subroutines in other
programming languages.
Matlab provides a large number of built-in functions that
perform computational tasks.
Fortunately the names of the built-in functions are very
similar to those commonly used in mathematics.
The general syntax is
output_value = function_name(input_value)

Jorma Kekalainen

Digital Image Processing

356

Some built-in functions


Exponential functions
MATLAB function
sqrt

Description
square root

Example
sqrt(2)

exp

exponential

exp(1)

Log
Log2

(natural) logarithm (base e) log( exp(2) )


log2(16)
logarithm base 2

log10

logarithm base10

Trigonometric
MATLAB
function
sin

functions
Description

log10(1e4)

sine

Example
sin(pi/6)

cos

cosine

cos(pi/3)

tan

tangent

tan(pi/4)

asin

inverse sine (arcsine)

asin(1/2)

acos

inverse cosine (arccos)

acos(1/2)

atan

inverse
tangent (arctan)
Digital Image Processing

atan(1)

Jorma Kekalainen

Lecture weeks 5 and 6

357

Page 78

Lecture notes

Digital Image Processing by Jorma Kekalainen

Note
The arguments of sin, cos, tan are always in
radians (not degrees).
The results of the inverse trigonometric
functions will also be in radians.

Jorma Kekalainen

Digital Image Processing

358

To call a function
Suppose that our workspace includes
variables A and B, such as
A = [1 3 5];
B = [10 6 4];
To call a function, enclose its input arguments
in parentheses:
max(A);

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

359

Page 79

Lecture notes

Digital Image Processing by Jorma Kekalainen

To call a function
If there are multiple input arguments, separate them with commas:
max(A,B);
Return output from a function by assigning it to a variable:
maxA = max(A);
When there are multiple output arguments, enclose them in square
brackets:
[maxA,location] = max(A);
Enclose any character string inputs in single quotes:
disp('hello world');
To call a function that does not require any inputs and does not
return any outputs, type only the function name:
clc
The clc function clears the Command Window.
Jorma Kekalainen

Digital Image Processing

360

Example
>> A=magic(5)
A=
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
>> [maxA,location] = max(A)
maxA =
23 24 25 21 22
location =
2 1 5 4 3
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

361

Page 80

Lecture notes

Digital Image Processing by Jorma Kekalainen

User defined functions


Functions are used to make the code more easily readable
and to implement new features in Matlab
Differences between functions and command string files:
function can be given parameters which affect the execution of the
function
function can have one or more return values or the result of the
function.
every function has its own workspace created when the function is
called and destroyed when the execution of the function ends
functions cannot directly utilize variables declared in Matlabs
workspace or internal variables in other functions
internal variables of the function are lost if they are not explicitly
returned or saved
Jorma Kekalainen

Digital Image Processing

362

Syntax and description of


function

Syntax:
function [y1,...,yN] = myfun(x1,...,xM)
Description:
function [y1,...,yN] = myfun(x1,...,xM)
declares a function named myfun that accepts
inputs x1,...,xM and returns outputs y1,...,yN.
This declaration statement must be the first
executable line of the function.
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

363

Page 81

Lecture notes

Digital Image Processing by Jorma Kekalainen

Naming and saving the function


Save the function code in a text file with a .m extension.
The name of the file should match the name of the first
function in the file.
Valid function names begin with an alphabetic character,
and can contain letters, numbers, or underscores.
We can declare multiple local functions within the same
file, or nest functions.
If any function in a file contains a nested function, all
functions in the file must use the end keyword to indicate
the end of the function.
Otherwise, the end keyword is optional.

Jorma Kekalainen

Digital Image Processing

364

Function m-files
When dealing with functions which will be
used in a variety of different programs, or
have multiple input and output arguments, or
require more complicated coding, then a
function m-file is required.
This is a m-file (a plain text file with a .m
extension) with a special header and then
Matlab commands to perform the required
calculations.
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

365

Page 82

Lecture notes

Digital Image Processing by Jorma Kekalainen

Function m-file header


The first non-comment line of a function m-file
must be
function [Out1, Out2, ...] = function_name(In1, In2, ...)
where In1, In2, ... are input arguments (typically at least
one, but often several), and Out1, Out2, ... are output
arguments (again there are typically one or more output
arguments).

If there is only one output argument, then the


square bracket are not required.
The Matlab keyword function must be present.
Jorma Kekalainen

Digital Image Processing

366

Input and output arguments


When calling a function, the order of the input and output
arguments determines which variables correspond.
For example if a function is defined by
function [Ret, Vol, Div] = process(Prices, Dates)

and called by
[x, y, z] = process(A, B)

then the variable A in the calling program gives the value of


the variable Prices in the function, and the variable B will
give the values for the variable Dates within the function.
The variables may be scalars, vectors, matrices, strings or
more complicated structures.
Similarly, the value of Vol calculated within the function will
give the value of the variable y in the calling program.
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

367

Page 83

Lecture notes

Digital Image Processing by Jorma Kekalainen

Write a function
Open a file in a text editor.
Within the file, declare the function and add program
statements:
function f = fact(n)
f = prod(1:n);

Function fact accepts a single input argument n, and


returns the factorial of n in output argument f.
The definition statement is the first executable line of
any function.
Each function definition includes these elements.
Jorma
Kekalainen definitions are not valid
Digitalat
Image
Processing
Note:
Function
the
command line or within a script.

368

Write a function
If our function returns more than one output, enclose the output
names in square brackets, such as
function [one,two,three] = myfunction(x)

The body of a function can include valid Matlab expressions, control


flow statements, comments, blank lines, and nested functions.
Any variables that we create within a function are stored within a
workspace specific to that function, which is separate from the base
workspace.
Functions end with either an end statement, the end of the file, or
the definition line for another function, whichever comes first.
The end statement is required only when a function in the file
contains a nested function (a function completely contained within
its parent).

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

369

Page 84

Lecture notes

Digital Image Processing by Jorma Kekalainen

Save the file and call the


function
Save the file (in this example, fact.m), either in the
current folder or in a folder on the Matlab search path.
Matlab looks for programs in these specific locations.
From the command line, call the new fact function to
calculate, say 10!, using the same syntax rules that
apply to calling functions installed with Matlab:
>>x = 10;
>>y = fact(x);

The variables that you pass to the function do not need


to have the same names as the arguments in the
function definition line.
Jorma Kekalainen

Digital Image Processing

370

Function in Editor Window

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

371

Page 85

Lecture notes

Digital Image Processing by Jorma Kekalainen

Parameters
Function is usually given one or more parameters
which it needs to execute its task
The following function avg_example(x) counts
the average value of the numbers given in
parameter vector
function [xmean]=avg_example(x)
% Getting the size of the vector
N = length(x);
% Counting the mean
xmean = 1 / N * sum(x);
Jorma
Kekalainen name = name of the
Digitalm-file.
Image Processing
Note:
Function

372

Example

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

373

Page 86

Lecture notes

Digital Image Processing by Jorma Kekalainen

Function calling from command


line
When the function is saved as avg_example.m, it can
be called from the command line in the usual manner.
>> numbers=1:10;
>> avg_example(numbers)
ans =
5.5000

>> numbers=(1:100);
>> avg_example(numbers)
ans =
50.5000

Functions can be given multiple parameters by listing


them all in parentheses after the function name
function weightedmean= weightedavg(x, w)

Jorma Kekalainen

Digital Image Processing

374

Return values
Return value in a function is declared as
follows:
function xmean = avg_example(x)
Variable xmean gets the value it has when the
function execution ends.
Returning multiple values is done in the same
manner:
function [xmean, N] = avg(x)
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

375

Page 87

Lecture notes

Digital Image Processing by Jorma Kekalainen

Function with multiple outputs


Define a function in a file named statistics.m that
returns the mean and standard deviation of an
input vector.
function [m,s] = statistics(x)
n = length(x);
m = sum(x)/n;
s = sqrt(sum((x-m).^2/n));
Call the function from the command line.
values =1:10;
[ave,stdev] = statistics(values)
Jorma Kekalainen

Digital Image Processing

376

Example

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

377

Page 88

Lecture notes

Digital Image Processing by Jorma Kekalainen

Digital Image Processing


Helping documentation

How to get help?


Command line help
every function has its own instructions and we can also write
instructions for your own functions! (the commented rows after
function declaration)
used when the name of the function is known but the details on how
to use it (parameters, return values) are not known or have been
forgotten

help command
Documentation (HTML-help)
more in-depth instructions, more examples, hyperlinks to related
commands

doc command or press the question mark in the upper part of


the Matlabs main window or press F1
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

379

Page 89

Lecture notes

Digital Image Processing by Jorma Kekalainen

Help

Jorma Kekalainen

Digital Image Processing

380

Help
Matlab comes with a vast amount of online help and
information.
So much, in fact, that it's quite easy to use Matlab
without a manual.
To obtain information on a particular command, we
can use help.
For example:
>> help for
FOR Repeat statements a specific number of times.
The general form of a FOR statement is:
FOR variable = expr, statement, ..., statement END
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

381

Page 90

Lecture notes

Digital Image Processing by Jorma Kekalainen

More help on help


If there is too much information, it may scroll past
too fast to see.
In such case we can turn on the Matlab pager
with the command
>> more on
For more help on help, try:
>> help help
Better formatted help can be obtained with the
doc function
>> doc help
Jorma Kekalainen

Digital Image Processing

382

More about the doc function


You can find more about the doc function with any of
>> doc doc
>> help doc
If you want to find help on a particular topic, but don't
know the function to use, the lookfor function is extremely
helpful.
The command
lookfor topic
lists all commands for which the first line of the help text
contains the string topic.
For example
>> lookfor exponential
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

383

Page 91

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
Suppose we want to find out if Matlab supports the
exponential function
>> lookfor exponential
EXP Exponential.
EXPINT Exponential integral function.
EXPM Matrix exponential.

Now we know that the function is implemented using exp.


>> lookfor exp

Note: Matlab convention is to use uppercase names for functions in help texts, even
Jorma Kekalainen
Image Processing
384
though
the function itself is called inDigital
lowercase.

Helping documentation
All MATLAB functions have supporting
documentation that includes examples and
describes the function inputs, outputs, and
calling syntax.
There are several ways to access this
information from the command line:
Open the function documentation in a separate
window using the doc command.

doc mean
Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

385

Page 92

Lecture notes

Digital Image Processing by Jorma Kekalainen

Helping documentation
Display function hints (the syntax portion of the
function documentation) in the Command Window by
pausing after you type the open parentheses for the
function input arguments.

mean(
View an abbreviated text version of the function
documentation in the Command Window using the
help command.

help mean
Access the complete product documentation by
clicking the help icon .
Jorma Kekalainen

Digital Image Processing

386

Exercise
Test and study all the previously presented
Matlab commands.

Jorma Kekalainen

Lecture weeks 5 and 6

Digital Image Processing

387

Page 93

Anda mungkin juga menyukai