Page 1
Lecture notes
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
204
Jorma Kekalainen
205
Page 2
Lecture notes
Jorma Kekalainen
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
207
Page 3
Lecture notes
Jorma Kekalainen
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
209
Page 4
Lecture notes
Current Folder
Jorma Kekalainen
210
Command Window
Jorma Kekalainen
211
Page 5
Lecture notes
Workspace
Jorma Kekalainen
212
Command History
Jorma Kekalainen
213
Page 6
Lecture notes
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
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
215
Page 7
Lecture notes
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
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
217
Page 8
Lecture notes
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
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
219
Page 9
Lecture notes
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
220
221
Page 10
Lecture notes
Jorma Kekalainen
222
223
Page 11
Lecture notes
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
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
Bytes
8
8
8
8
8
8
Class Attributes
double
double
double
double
double
double
Digital Image
Processing
225
Page 12
Lecture notes
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
227
Page 13
Lecture notes
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
228
Example
>> whos
Name Size
ans
c
Jorma Kekalainen
1x1
1x4
Bytes Class
Attributes
16 double complex
64 double complex
229
Page 14
Lecture notes
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
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
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
231
Page 15
Lecture notes
Workspace pane
The variables also appear in the Workspace
pane on the desktop.
Jorma Kekalainen
232
Jorma Kekalainen
233
Page 16
Lecture notes
235
Page 17
Lecture notes
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
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
237
Page 18
Lecture notes
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
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
239
Page 19
Lecture notes
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
241
Page 20
Lecture notes
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
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
243
Page 21
Lecture notes
Note
Jorma Kekalainen
244
1 17
245
Page 22
Lecture notes
>>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
246
247
Page 23
Lecture notes
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
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
249
Page 24
Lecture notes
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
250
251
Page 25
Lecture notes
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
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
253
Page 26
Lecture notes
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
255
Page 27
Lecture notes
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
257
Page 28
Lecture notes
Example
As an example of matrix powers:
>> a^3*b^4
ans =
Jorma Kekalainen
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
259
Page 29
Lecture notes
>> fliplr(a)
ans =
Jorma Kekalainen
260
Jorma Kekalainen
90
261
Page 30
Lecture notes
3
6
10
262
Jorma Kekalainen
1
4
7
2 3
5 6
263
8 10
Page 31
Lecture notes
264
Note
Jorma Kekalainen
265
Page 32
Lecture notes
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
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
267
Page 33
Lecture notes
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
269
Page 34
Lecture notes
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.
Jorma Kekalainen
1
4
7
2 3
5 6
271
8 10
Page 35
Lecture notes
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
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
273
Page 36
Lecture notes
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
274
Example
Jorma Kekalainen
>> 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
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
276
277
Page 38
Lecture notes
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
279
Page 39
Lecture notes
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
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.
Page 40
Lecture notes
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
283
Page 41
Lecture notes
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
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
285
Page 42
Lecture notes
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
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
287
Page 43
Lecture notes
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.
Page 44
Lecture notes
Basic commands
Jorma Kekalainen
290
291
Page 45
Lecture notes
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
292
Example
x=[0:0.1:2*pi];
plot(x,sin(x))
and the result is shown
beside.
Jorma Kekalainen
A simple plot
293
Page 46
Lecture notes
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
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
295
Page 47
Lecture notes
Example
We can label the axes and add a title.
title('Plot of the Cosine Function')
xlabel('x')
ylabel('cos(x)')
Jorma Kekalainen
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
297
Page 48
Lecture notes
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
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
299
Page 49
Lecture notes
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
300
Note
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
301
Page 50
Lecture notes
Note
Explanation for the title:
302
Example
Basic command: plot
Jorma Kekalainen
303
Page 51
Lecture notes
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
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)')
305
Page 52
Lecture notes
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
306
3-D plots
Then, create a surface plot.
surf(X,Y,Z)
Jorma Kekalainen
307
Page 53
Lecture notes
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
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');
309
Page 54
Lecture notes
Example: Subplots
Jorma Kekalainen
310
Page 55
Lecture notes
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
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
1x13
26 char
Digital Image Processing
313
Page 56
Lecture notes
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
314
Jorma Kekalainen
315
Page 57
Lecture notes
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
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
317
Page 58
Lecture notes
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
Page 59
Lecture notes
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
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
321
Page 60
Lecture notes
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
323
Page 61
Lecture notes
Creating a script
Jorma Kekalainen
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
325
Page 62
Lecture notes
Jorma Kekalainen
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
327
Page 63
Lecture notes
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
end
328
Branching
switch x
case 1
% code1
case 2
% code2
case {3, 4}
% code34
otherwise
% code
(optional
end
Jorma Kekalainen
x=1
x=2
x=3, x=4
otherwise
329
Page 64
Lecture notes
>> 3 < 4
ans =
1
>> 3 > 4
ans =
0
Jorma Kekalainen
330
Example
331
Page 65
Lecture notes
>> 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
index =
-5
index =
-3
index =
-1
333
Page 66
Lecture notes
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
335
Page 67
Lecture notes
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
336
Jorma Kekalainen
337
Page 68
Lecture notes
Example
How much is x?
>> a = 0;
while (2)
a = a + 1;
end
>> a
a=
304383259
Jorma Kekalainen
338
Jorma Kekalainen
339
Page 69
Lecture notes
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
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
341
Page 70
Lecture notes
342
Jorma Kekalainen
343
Page 71
Lecture notes
344
Jorma Kekalainen
345
Page 72
Lecture notes
Iteration #4
sampleMean =
Iteration #5
sampleMean =
overallMean =
0.4884
Jorma Kekalainen
346
347
Page 73
Lecture notes
Jorma Kekalainen
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
349
Page 74
Lecture notes
350
Jorma Kekalainen
351
Page 75
Lecture notes
Jorma Kekalainen
352
353
Page 76
Lecture notes
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
354
Page 77
Lecture notes
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
356
Description
square root
Example
sqrt(2)
exp
exponential
exp(1)
Log
Log2
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
asin(1/2)
acos
acos(1/2)
atan
inverse
tangent (arctan)
Digital Image Processing
atan(1)
Jorma Kekalainen
357
Page 78
Lecture notes
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
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
359
Page 79
Lecture notes
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
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
361
Page 80
Lecture notes
362
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
363
Page 81
Lecture notes
Jorma Kekalainen
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
365
Page 82
Lecture notes
366
and called by
[x, y, z] = process(A, B)
367
Page 83
Lecture notes
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);
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)
Jorma Kekalainen
369
Page 84
Lecture notes
370
Jorma Kekalainen
371
Page 85
Lecture notes
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
373
Page 86
Lecture notes
>> numbers=(1:100);
>> avg_example(numbers)
ans =
50.5000
Jorma Kekalainen
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
375
Page 87
Lecture notes
376
Example
Jorma Kekalainen
377
Page 88
Lecture notes
help command
Documentation (HTML-help)
more in-depth instructions, more examples, hyperlinks to related
commands
379
Page 89
Lecture notes
Help
Jorma Kekalainen
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
381
Page 90
Lecture notes
382
383
Page 91
Lecture notes
Example
Suppose we want to find out if Matlab supports the
exponential function
>> lookfor exponential
EXP Exponential.
EXPINT Exponential integral function.
EXPM Matrix exponential.
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
385
Page 92
Lecture notes
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
386
Exercise
Test and study all the previously presented
Matlab commands.
Jorma Kekalainen
387
Page 93