Professional Documents
Culture Documents
MATLAB
s a powerful computing system for handling scientific and engineering calculations. The
name MATLAB stands for Matrix Laboratory, because the system was designed to make
matrix computations particularly easy. A matrix is an array of numbers organized in m rows
and n columns. An example is the following m n = 2 3 array:
Any one of the elements in a matrix can be plucked out by using the row
and column indices that identify its location. The elements in this example
are plucked out as follows: A(1, 1) = 1, A(1, 2) = 3, A(1, 3) = 5, A(2, 1) = 2,
A(2, 2) = 4, A(2, 3) = 6. The first index identifies the row number counted from
top to bottom; the second index is the column number counted from left to
right. This is the convention used in MATLAB to locate information in an array.
One of the many things you will like about MATLAB (and that distinguishes
it from many other computer programming systems, such as C++ and Java) is
that you can use it interactively. This means you type some commands at the
special MATLAB prompt and get results immediately. The problems solved in
this way can be very simple, like finding a square root, or very complicated, like
finding the solution to a system of differential equations. For many technical
problems, you enter only one or two commandsMATLAB does most of the
work for you.
There are three essential requirements for successful MATLAB applications:
You must learn the exact rules for writing MATLAB statements and
using MATLAB utilities.
You must know the mathematics associated with the problem you
RAMI HAKKI MATLAB AND IMAGE PROCESSING
want to solve.
You must develop a logical plan of attackthe algorithmfor solving
a particular problem.
Figure 1.1
MATLAB desktop
Help :
MATLAB has a very useful Help system, which we will look at in a little more
detail. For the moment type help at the command line to see all the Help categories. For
example, type help elfun to see all MATLABs elementary mathematical functions. Another
utility, lookfor, enables you to search for a particular string in the Help text of functions
(e.g., lookfor eigenvalue displays all functions relating to eigenvalues).
Script Files:
Script files are ordinary ASCII (text) files that contain Matlab commands. It is essential that
such files have names having an extension .m (e.g., myfile.m) and, for this reason, they are
commonly known as m-files. The commands in this file may then be executed using
>> myfile
Note: the command does not include the file name extension .m.
Script files are created with the built-in editor (it is possible to change to your favourite
editor in the Preferences window).
Any text that follows % on a line is ignored. This enables descriptive comments to be
included. It is possible, via a mouse menu, to highlight commands that appear in the
Command History click to create a script file. Cut and Paste can
be used to copy individual commands from the Command History window into a script
file.
Data Types :
Numeric Types
Integer and floating-point data
Tables
Arrays in tabular form whose named columns can have different types
Structures
Arrays with named fields that can contain data of varying types and sizes
Cell Arrays
Arrays that can contain data of varying types and sizes
Arithmetic :
Since we have experience doing arithmetic, we want to examine if MATLAB
does it correctly. This is a required step to gain confidence in any tool and in
our ability to use it.
Type 2+3 after the prompt, followed by Enter (press the Enter key) as
indicated by <Enter>:
2+3 | 32
2*3 | 1/2
23 | 2\1 | 2 .* 3 | 1 ./ 2 | 2 . 3
( NOTE : A period in front of the *, /, and , respectively, does not change the results because the
multiplication, division, and exponentiation is done with single numbers. (An explanation for the need for
these symbols is provided later when
we deal with arrays of numbers.))
Relational Operations :
Syntax
A<B
A>B
A <= B
A >= B
A == B
A ~= B
Useful function :
Isequal
tf = isequal(A,B) // returns logical 1 (true) if A and B are the same size and their contents are of equal
value; otherwise, it returns logical 0 (false). The test compares both real and imaginary parts of numeric
arrays. isequal ignores the data type of the values in determining whether they are equal.
Intersect
Set intersection of two arrays
C = intersect(A,B) // returns the data common to both A and B with no repetitions .
Union
C = union(A,B) returns the combined data from A and B with no repetitions.
If A and B are numeric arrays, logical arrays, character arrays, categorical arrays, or cell
arrays of strings, then union returns the combined values from A and B. The values of C are
in sorted order.
If A and B are tables, then union returns the combined set of rows from both tables. The
rows of table C are in sorted order.
Another example :
Intersection of Two Tables
Define two tables with rows in common.
A = table([1:5]',['A';'B';'C';'D';'E'],logical([0;1;0;1;0]))
B = table([1:2:10]',['A';'C';'E';'G';'I'],logical(zeros(5,1)))
A=
Var1
Var2
Var3
----
----
-----
false
true
false
true
false
B=
Var1
Var2
Var3
----
----
-----
false
false
false
false
false
Var2
Var3
----
----
-----
false
false
false
NOTE :
Table () Function
T = table(var1,...,varN) creates a table from the input variables, var1,...,varN . Variables can
be of different sizes and data types, but all variables must have the same number of rows.
If the inputs are workspace variables, table uses the workspace variable names as variable
names for the table. Otherwise, table uses strings of the form 'Var1',...,'VarN' where N is the
number of variables.
Example :
Create Table from Workspace Variables
Define workspace variables with the same number of rows.
LastName = {'Smith';'Johnson';'Williams';'Jones';'Brown'};
Age = [38;43;38;40;49];
Height = [71;69;64;67;64];
Weight = [176;163;131;133;119];
BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80];
Create a table, T, as a container for the workspace variables.
T = table(Age,Height,Weight,BloodPressure,...
'RowNames',LastName)
T=
Age Height Weight
BloodPressure
38
43
71
69
176
163
124
109
93
77
Williams 38
Jones
Brown
40
49
64
67
64
131
133
125
117
119
122
83
75
80
Notice table names the variables with the workspace variable names.
Elementary Functions :
These include sqrt, exp, log, log10
x=9;
sqrt(x), exp(x), log(sqrt(x)), log10(x^2+6)
ans = 3
ans = 8.1031e+03
ans = 1.0986
ans = 1.9395
exp(x) denotes the exponential function exp(x) = ex and the inverse function is log:
Tips :
Clear : delete a specific variable defined after it .
Clc : clear the current commands in command window .
Close : close specific figure defined after it or can close whole figure by type all .
Whos : is executed to determine the list of local variables or commands presently in the workspace .
Vectors :
Variables such as a=2 and b=5 above are called scalars; they are single-valued. MATLAB
also handles vectors (generally referred to as arrays), which are the key to many of its
powerful features. The easiest way of defining a vector where the elements (components)
increase by the same amount is with a statement like
x = first element : step : last element .
or
x = linspace(first element, last element );
you can also find the size of vectors by using size () commend .
which return the n x m diminutions of the input array .
To get a vector's length, use the length function .
10
[X,Y] = meshgrid(gv) is the same as [X,Y] = meshgrid(gv,gv). In other words, you can
reuse the same grid vector in each respective dimension. The dimensionality of the output
arrays is determined by the number of output arguments.
The output coordinate arrays are typically used to evaluate functions of two or three
variables. They are also frequently used to create surface and volumetric plots.
Z = X .* exp(-X.^2 - Y.^2);
surf(X,Y,Z)
11
Figure 1.2 shows the function Z(x,y) in 3 domination representation with respect to already entered
space domain [X,Y]
Transposing :
We can convert a row vector into a column vector (and vice versa) by a process called
transposing which is denoted by .
w, w, c, c
w=
1 -2 3
w=
1
-2
3
c=
1.0000
3.0000
2.2361
c =
1.0000 3.0000 2.2361
12
t = w + 2*c
t=
3.0000 4.0000 7.4721
T = 5*w-2*c
T=
3.0000
-16.0000
10.5279
If x is a complex vector, then x gives the complex conjugate transpose of x:
x = [1+3i, 2-2i]
ans =
1.0000 + 3.0000i 2.0000 - 2.0000i
x
ans =
1.0000 - 3.0000i
2.0000 + 2.0000i
Note that the components of x were defined without a * operator; this means of defining
complex numbers works even when the variable i already has a numeric value. To obtain
the plain transpose of a complex number use . as in x.
One must be aware at all times, as the next example shows:
i=3; [1+2i, 3-i, 3-1i] // if you typed the numbers without putting * operator matlab will understand the
statement as a complex number even you defined i as a scalar .
ans =
1.0000 + 2.0000i 0 3.0000 - 1.0000i
in which only the 2nd element has been influenced by the value of the variable i.
13
You can also modulate the signal and shift it to right or left easily by the following
operation :
z=sin (x-T) , z=sin (x+T) where T is the time to be shifted .
Multiplying the signal in a factor A can easily change the magnitude :
A=0.6 ; Z=A*sin (x) ;
Another tip :
Windowing
14
Figure 1.3
Plotting the to signals of sin(x) with windowing property above and without below.
Example (2) :
drawing two functions in the same plot graph Plot Multiple Lines Define x as 100 linearly
spaced values between -2 and +2 . Define y1 and y2 as sine and cosine values of x.
Create a line plot of both sets of data.
15
Figure 1.4
Do you know?
In plot function you can change the color and the line style by apply the following symbols
as a string to plot () expression between to quotations
16
Arrays :
Special Matrices :
Matlab provides a number of useful builtin matrices of any desired size.
ones(m,n) gives an m n matrix of 1s,
P = ones(2,3)
P=
111
111
zeros(m,n) gives an m n matrix of 0s,
Z = zeros(2,3), zeros(size(P))
Z=
000
000
ans =
00
00
00
The second command illustrates how we can
construct a matrix based on the size of an existing one. Try ones(size(D)).
An n n matrix that has the same number of rows and columns and is called a square
matrix.
A matrix is said to be symmetric if it is equal to its transpose (i.e. it is unchanged by
transposition):
S = [2 -1 0; -1 2 -1; 0 -1 2],
S=
2 -1 0
-1 2 -1
0 -1 2
17
St = S
St =
2 -1 0
-1 2 -1
0 -1 2
S-St
ans =
000
000
000
Diagonal Matrices :
A diagonal matrix is similar to the identity matrix except that its diagonal entries are not
necessarily equal to 1.
D=
RAMI HAKKI MATLAB AND IMAGE PROCESSING
18
3 0 0
040
002
is a 3 3 diagonal matrix. To construct this in Matlab, we could either type it in directly
D = [-3 0 0; 0 4 0; 0 0 2]
D=
-3 0 0
040
002
but this becomes impractical when the dimension is large (e.g. a 100 100 diagonal
matrix).
We then use the diag function. first define a vector d, say, containing the values of the
diagonal entries (in order) then diag(d) gives the required matrix.
d = [-3 4 2], D = diag(d)
d=
-3 4 2
D=
-3 0 0
040
002
On the other hand, if A is any matrix, the command diag(A) extracts its diagonal entries:
F = [0 1 8 7; 3 -2 -4 2; 4 2 1 1]
F=
0 1 8 7
3 -2 -4 2
4 2 1 1
diag(F)
ans =
0
-2
1
Notice that the matrix does not have to be square.
NOTE :
D = diag(v) returns a square diagonal matrix with the elements of vector v on the main
(k=0) diagonal.
19
Building Matrices :
It is often convenient to build large matrices
from smaller ones:
C=[0 1; 3 -2; 4 2]; x=[8;-4;1];
G = [C x]
G=
018
3 -2 -4
421
A, B, H = [A; B]
A=
5 7 9
1 -3 -7
B=
-1 2 5
905
H=
5 7 9
1 -3 -7
-1 2 5
9 0 5
so we have added an extra column (x) to C in order to form G and have stacked A and B on
top of each other to form H.
J = [1:4; 5:8; 9:12; 20 0 5 4]
J=
1234
5678
9 10 11 12
20 0 5 4
K = [ diag(1:4) J; J zeros(4,4)]
K=
10001 2 3 4
02005 6 7 8
20
0 0 3 0 9 10 11 12
0 0 0 4 20 0 5 4
1 5 9 20 0 0 0 0
2 6 10 0 0 0 0 0
3 7 11 5 0 0 0 0
4 8 12 4 0 0 0 0
The command spy(K) will produce a graphical display of the location of the nonzero entries
in K (it will also give a value for nzthe number of nonzero entries):
spy(K), grid
Bandwidth :
Lower and upper matrix bandwidth
B = bandwidth(A,type) // returns the bandwidth of matrix A specified by type. Specify type as 'lower'
for the lower bandwidth, or 'upper' for the upper bandwidth.
A=
35
3 32
31
5 34 12 14
8 28 33 17
30
4 36 29 13 18 11
Find the lower bandwidth of A by specifying type as 'lower'.
B = bandwidth(A,'lower')
B=
21
5
The result is 5 because every diagonal below the main diagonal has nonzero elements.
Find the upper bandwidth of A by specifying type as 'upper'.
B = bandwidth(A,'upper')
B=
0
The result is 0 because there are no nonzero elements above the main diagonal .
Essinatial functions :
det / Matrix determinant
d = det(X) // returns the determinant of the square matrix X.
rank
k = rank(A) // returns the number of singular values of A that are larger than the default tolerance .
The rank function provides an estimate of the number of linearly independent rows or columns of a full matrix.
trace
b = trace(A) is the sum of the diagonal elements of the matrix A.
norm
n = norm(X) // If X is a vector, this is equal to the Euclidean distance. If X is a matrix, this is equal to the
largest singular value of X.
Statistics :
Descriptive Statistics
Range, central tendency, standard deviation, variance, correlation
Covariance matrix :
C = cov(x), if x is a vector, returns the variance of x. For matrix input X, where each row is
an observation, and each column is a variable, cov(X) is the covariance matrix.
diag(cov(X)) is a vector of variances for each column, and sqrt(diag(cov(X))) is a vector of
standard deviations
The covariance between two random variables is:
22
Loops :
There are cases that we want to repeat a segment of code a number of different times
A standard for loop has the form
>> for counter = 1:20
.......
end
which repeats the code as far as the end with the variable counter=1 the first time,
counter=2 the second time, and so forth. Rather more generally
>> for counter = [23 11 19 5.4 6]
.......
end
repeats the code with counter=23 the first time, counter=11 the second time, and so forth .
Example
The Fibonnaci sequence starts off with the numbers 0 and 1, then succeeding terms are the
sum of its two immediate predecessors. Mathematically, f1 = 0, f2 = 1 and
fn = fn1 + fn2, n = 3, 4, 5, . . . .
Test the emphasis that the ratio fn1/fn of two successive values approaches the golden
ratio
(5 1)/2 = 0.6180 . . ..
RAMI HAKKI MATLAB AND IMAGE PROCESSING
23
While Loops
There are some occasions when we want to repeat a section of Matlab code until some
logical condition is satisfied, but we cannot tell in advance how many times we have to go
around the loop. This we can do with a while...end construct.
Example
What is the greatest value of n that can be used in the sum
12 + 22 + + n2
and get a value of less than 100?
>> S = 1; n = 2;
>> while S+ n^2 < 100
S = S + n^2; n = n+1;
end
RAMI HAKKI MATLAB AND IMAGE PROCESSING
24
>> [n-1, S]
ans =
6 91
The lines of code between while and end will only be executed if the condition S+n^2 < 100
is true.
Exercise
Replace 100 in the previous example by 10 and work through the lines of code by hand.
You should get the answers n = 2 and S = 5.
if...then...else...end
This allows us to execute different commands depending on the truth or falsity of some
logical tests. To test whether or not ^e is greater than, or equal to, e^:
>> a = pi^exp(1); c = exp(pi);
>> if a >= c
b = sqrt(a^2 - c^2)
end
so that b is assigned a value only if a c. There is no output so we deduce that a = ^e < c
= e^.
A more common situation is
>> if a >= c
b = sqrt(a^2 - c^2)
else
b=0
end
b=
0
which ensures that b is always assigned a value
and confirming that a < c.
Note :
If you want to input the value of the variables by yourself you can use
result = input(prompt) // displays the prompt string on the screen, waits for input from the
keyboard, evaluates any expressions in the input, and returns the result. To evaluate expressions, the input
function can use variables in the current workspace.
If you press the Return key without entering anything, then input returns an empty
matrix.
25
Random Numbers
The function rand(m,n) produces an mn matrix of random numbers, each of which is in
the range 0 to 1. rand on its own produces a single random number.
>> y = rand, Y = rand(2,3)
y=
0.9191
Y=
0.6262 0.1575 0.2520
0.7446 0.7764 0.6121
Repeating these commands will lead to different answers.
26
37 38 39
>> hold on, plot(x(k),y(k),o)
>> km = find( x>0.5 & y<0)
km =
32 33 34
>> plot(x(km),y(km),-)
Logicals
Matlab represents true and false by means of the integers 0 and 1.
true = 1, false = 0
If at some point in a calculation a scalar x, say, has been assigned a value, we may make
certain logical tests on it:
x == 2 is x equal to 2?
RAMI HAKKI MATLAB AND IMAGE PROCESSING
27
x ~= 2 is x not equal to 2?
x > 2 is x greater than 2?
x < 2 is x less than 2?
x >= 2 is x greater than or equal to 2?
x <= 2 is x less than or equal to 2?
Pay particular attention to the fact that the
test for equality involves two equal signs ==.
>> x = pi
x=
3.1416
>> x ~= 3, x ~= pi
ans =
1
ans =
0
When x is a vector or a matrix, these tests are performed elementwise:
x=
-2.0000 3.1416 5.0000
-1.0000 0 1.0000
>> x == 0
ans =
000
010
>> x > 1, x >=-1
ans =
011
000
ans =
011
111
We may combine logical tests, as in
>> x
x=
-2.0000 3.1416 5.0000
-5.0000 -3.0000 -1.0000
>> x > 3 & x < 4
ans =
010
000
RAMI HAKKI MATLAB AND IMAGE PROCESSING
28
>> x > 3 | x == -3
ans =
011
010
As one might expect, & represents and and (not so clearly) the vertical bar | means or; also
~means not as in ~= (not equal), ~(x>0), etc.
Linear equations :
Systems of linear equations are very important in engineering and scientific analysis. A
simple example is finding the solution to two simultaneous
equations:
x + 2y = 4
2x y = 3
Here are two approaches to the solution. Matrix method. Type the following commands
(exactly as they are):
a = [1 2; 2 1];
b = [4; 3];
x = a\b
the result is
x=
2
1
i.e., x = 2, y = 1.
Or by using solve function as described below:
Solve (eq, x) returns the set of all complex solutions of an equation or inequality eq with respect to x.
29
syms x
s=solve('x^4 - 5*x^2 + 6*x = 2', x) // defining a liner equation that deal with variable x which
already a symbolic variable .
s=
1
1
3^(1/2) - 1
- 3^(1/2) - 1
30