You are on page 1of 31

CHAPTER 1 INTRODUCTION TO MATLAB FUNDAMENTIAL

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).

RAMI HAKKI MATLAB AND IMAGE PROCESSING

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

Characters and Strings


Text in character arrays

Tables

RAMI HAKKI MATLAB AND IMAGE PROCESSING

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.))

RAMI HAKKI MATLAB AND IMAGE PROCESSING

Complex numbers in matlab :


1i returns the basic imaginary unit. i is equivalent to sqrt(-1). You can use i to enter
complex numbers. You also can use the character j as the imaginary unit. To create a
complex number without using i and j, use the complex(x,y) function.
z = a + bi returns a complex numerical constant, z.
Matlab recognizes several different kinds of numbers

The e notation is used for very large or very small numbers:


-1.3412e+03 = 1.3412 103 = 1341.2
-1.3412e-01 = 1.3412 101 = 0.13412
All computations in MATLAB are done in double precision, which means about 15
significant figures.
How Matlab prints numbers is controlled by the format command. Type help
format for full list. Should you wish to switch back to the default format then format will
suffice.

RAMI HAKKI MATLAB AND IMAGE PROCESSING

Relational Operations :
Syntax
A<B
A>B
A <= B
A >= B
A == B
A ~= B

Example and how to :


If one of the operands is a scalar and the other a matrix, the scalar expands to the size of the
matrix. For example, the two pairs of statements .
X = 5; X >= [1 2 3; 4 5 6; 7 8 10]
ans =
1

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 .

RAMI HAKKI MATLAB AND IMAGE PROCESSING

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.

Example : Intersection of Two Vectors


Define two vectors with values in common.
A = [7 1 7 7 4]; B = [7 0 4 4 0];
Find the values common to both A and B.
C = intersect(A,B)
C= 4

Union of Two Vectors


Define two vectors with a value in common.
A = [5 7 1]; B = [3 1 1];
Find the union of vectors A and B.
C = union(A,B)
C= 1

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)))

RAMI HAKKI MATLAB AND IMAGE PROCESSING

A=
Var1

Var2

Var3

----

----

-----

false

true

false

true

false

B=
Var1

Var2

Var3

----

----

-----

false

false

false

false

false

Find the rows common to both A and B.


C = intersect(A,B)
C=
Var1

Var2

Var3

----

----

-----

false

false

false

RAMI HAKKI MATLAB AND IMAGE PROCESSING

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

___ ______ ______ _______________


Smith
Johnson

38
43

71
69

176
163

RAMI HAKKI MATLAB AND IMAGE PROCESSING

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:

format long e, exp(log(9)), log(exp(9))


ans = 9.000000000000002e+00
ans = 9

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 :

RAMI HAKKI MATLAB AND IMAGE PROCESSING

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 .

Generate logarithmically spaced vectors :


The logspace function generates logarithmically spaced vectors. Especially useful for
creating frequency vectors, it is a logarithmic equivalent of linspace and the ":" or colon
operator
y = logspace (a,b) // generates a row vector y of 50 logarithmically spaced points between decades
10^a and 10^b.

y = logspace(a,b,n) generates n points between decades 10^a and 10^b .

Creating space domain :


[X,Y] = meshgrid(xgv,ygv) replicates the grid vectors xgv and ygv to produce a full grid.
This grid is represented by the output coordinate arrays X and Y. The output coordinate
arrays X and Y contain copies of the grid vectors xgv and ygv respectively. The sizes of the
output arrays are determined by the length of the grid vectors. For grid vectors xgv and ygv
of length M and N respectively, X and Y will have N rows and M columns.
[X,Y,Z] = meshgrid(xgv,ygv,zgv) produces three-dimensional coordinate arrays. The
output coordinate arrays X, Y, and Z contain copies of the grid vectors xgv, ygv, and zgv
respectively. The sizes of the output arrays are determined by the length of the grid vectors.
For grid vectors xgv, ygv, and zgv of length M, N, and P respectively, X, Y, and Z will
have N rows, M columns, and P pages.

RAMI HAKKI MATLAB AND IMAGE PROCESSING

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.

[X,Y,Z] = meshgrid(gv) is the same as [X,Y,Z] = meshgrid(gv,gv,gv). Again, 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.

Example and how to :


Plot 3-D Functional Surface
Use meshgrid to create a gridded (X,Y) domain.
[X,Y] = meshgrid(-2:.2:2, -2:.2:2);
Evaluate the function
results.

over this domain and generate a surface plot of the

Z = X .* exp(-X.^2 - Y.^2);
surf(X,Y,Z)

RAMI HAKKI MATLAB AND IMAGE PROCESSING

11

Figure 1.2 shows the function Z(x,y) in 3 domination representation with respect to already entered
space domain [X,Y]

Extracting Parts of Vectors :


r = [1:2:6, -1:-2:-7]
r=
1 3 5 -1 -3 -5 -7
To get the 3rd to 6th entries:
r(3:6)
ans =
5 -1 -3 -5
To get alternate entries:
r(1:2:7)
ans =
1 5 -3 -7

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

RAMI HAKKI MATLAB AND IMAGE PROCESSING

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.

Example and how to :

RAMI HAKKI MATLAB AND IMAGE PROCESSING

13

x = 0 : 0.1 : 10; // time vector .


z = sin (x) ; // function of x .
plot(x,z), grid // draw 2d graph with guiding grids .

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

x=1:0.1:100 ; // define time domain vector .


y=sin(x); // define function of x .
z=zeros(1,1000) ;
z(40:600)=1 ; // define window of 560 element .
y2=y.*z ;
subplot(2,1,1) , plot(x,y2)
hold on
subplot(2,1,2) , plot(x,y)

RAMI HAKKI MATLAB AND IMAGE PROCESSING

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.

x = linspace(-2*pi,2*pi); // define time vector .


y1 = sin(x);
y2 = cos(x);
figure
plot(x,y1,x,y2)

RAMI HAKKI MATLAB AND IMAGE PROCESSING

15

Figure 1.4

shows two sinusoids signals differs in pi/2 radian .

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

RAMI HAKKI MATLAB AND IMAGE PROCESSING

16

Arrays :

Like other programming languages, arrays are an important part of MATLAB


Two types of arrays
(1) matrix of numbers (either double or complex )
(2) cell array of objects (more advanced data structure)

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

RAMI HAKKI MATLAB AND IMAGE PROCESSING

17

St = S
St =
2 -1 0
-1 2 -1
0 -1 2
S-St
ans =
000
000
000

The Identity Matrix :


The n n identity matrix is a matrix of zeros except for having ones along its leading
diagonal (top left to bottom right). This is called eye(n) in Matlab (since mathematically it
is usually denoted by I).
I = eye(3), x = [8; -4; 1], I*x
I=
100
010
001
x=
8
-4
1
ans =
8
-4
1
Notice that multiplying the 3 1 vector x by the 3 3 identity I has no effect (it is like
multiplying a number by 1).

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.

RAMI HAKKI MATLAB AND IMAGE PROCESSING

19

x = diag(A) returns a column vector of the main (k=0) diagonal elements of A.

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

RAMI HAKKI MATLAB AND IMAGE PROCESSING

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.

Example and how to :


Create a 6-by-6 lower triangular matrix.
A = tril(magic(6)) // Lower triangular part of matrix

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=

RAMI HAKKI MATLAB AND IMAGE PROCESSING

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:

RAMI HAKKI MATLAB AND IMAGE PROCESSING

22

where E is the mathematical expectation and i = Exi.


Another functions :

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

>> F(1) = 0; F(2) = 1;


>> for i = 3:20
F(i) = F(i-1) + F(i-2);
end
>> plot(1:19, F(1:19)./F(2:20),o )
>> hold on, xlabel(n)
>> plot(1:19, F(1:19)./F(2:20),- )
>> legend(Ratio of terms f_{n-1}/f_n)
>> plot([0 20], (sqrt(5)-1)/2*[1,1],--)
The last of these commands produces the dashed horizontal line.

Figure 1.5 Shows the output plot of Fibonnaci sequence

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.

RAMI HAKKI MATLAB AND IMAGE PROCESSING

25

The sum Function :


The sum applied to a vector adds up its components (as in sum(1:10)) while, for a
matrix, it adds up the components in each column and returns a row vector.
sum(sum(A)) then sums all the entries of A.
>> A = [1:3; 4:6; 7:9]
A=
123
456
789
>> s = sum(A), ss = sum(sum(A))
s=
12 15 18
ss =
45

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.

find for vectors


The function find returns a list of the positions (indices) of the elements of a vector
satisfying a given condition. For example,
>> x = -1:.05:1;
>> y = sin(3*pi*x).*exp(-x.^2);
>> plot(x,y,:)
>> k = find(y > 0.2)
k=
Columns 1 through 12
9 10 11 12 13 22 23 24 25 26 27 36
Columns 13 through 15

RAMI HAKKI MATLAB AND IMAGE PROCESSING

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),-)

Figure 1.6 Shows the last example plot graph


Timing
Matlab allows the timing of sections of code by providing the functions tic and toc. tic
switches on a stopwatch while toc stops it and returns the CPU time (Central Processor
Unit) in seconds. The timings will vary depending on the model of computer being used and
its current load.
tic, sum((1:10000).^2);toc
Elapsed time is 0.000124 seconds.

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.

Example and how to :


RAMI HAKKI MATLAB AND IMAGE PROCESSING

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

End of chapter (1)

RAMI HAKKI MATLAB AND IMAGE PROCESSING

30

You might also like