Tải bản đầy đủ (.pdf) (33 trang)

MATLAB Primer

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (351.93 KB, 33 trang )

CHAPTER 9
MATLAB Primer
9.1 INTRODUCTION
MATLAB is a very powerful and well-known software package
1
that is used
in science and engineering disciplines, for numerical computation, data analysis,
and graphical visualization. It is available in almost all platforms such as personal
computers, and workstations running under several operating systems. When you
begin a session by typing the command
matlab
, the first window displayed on
the monitor is the command window with the prompt
>>
, which is waiting for
your command.
2
Use the command
exit
to end the session.
MATLAB contains a large collection of built-in functions and commands that
are used in an interactive mode, when you are in the command window. As soon
as the name of a function or a command is typed at the prompt in the command
window, with the proper syntax, the answer is displayed immediately. But there
are two other windows, the edit window and graphics window, which will be dis-
cussed later. The software package is designed to use additional sets of functions
that are more applicable in particular disciplines such as control systems, digital
signal processing, communications engineering, and image processing. There are
more than 20 sets known as “toolboxes” (e.g., control toolbox, digital signal pro-
cessing toolbox, communication toolbox, image processing toolbox). All of them
run under MATLAB and implement the functions on the basis of matrix manipu-


lation of numerical data, and that is why the software is called MATLAB (matrix
laboratory). Simulink is another toolbox that is used to simulate the performance
of the systems, when the systems are built by connecting individual blocks rep-
resenting different subsystems and the output is obtained when the systems are
1
The software is available from The MathWorks, Inc., 3 Apple Hill Drive, Natick, MA
01760-2098, phone 508-647-7000, fax 508-647-7001, email

, Website
.
2
If you are logging on a workstation connected to a computer network, you may have to set the
proper environment by typing
setenv DISPLAY network number:
or some other com-
mand before launching MATLAB.
Introduction to Digital Signal Processing and Filter Design, by B. A. Shenoi
Copyright © 2006 John Wiley & Sons, Inc.
391
392
MATLAB PRIMER
subjected to different kinds of input signals. MATLAB allows us to construct
new functions using the enormous number of built-in functions, commands, and
operations in MATLAB and in the many toolboxes, without having to know how
to compile, link, load, and create executable code, because MATLAB uses its own
language to carry out all these steps, which are invisible to the user. It carries out
the steps and gives the answer very fast! In most versions of MATLAB, there is
a “symbol” toolbox, which performs does symbolic operations such as differen-
tiation, integration, matrix inversion, and solution of differential equations when
the operations are expressed in their symbolic form. In more recent versions of

this software, new toolboxes such as Filter Design Toolbox and DSP Blockset,
which are based on the object-oriented programming features of MATLAB, have
been added. These have been treated in some chapters of this book.
9.1.1 Vectors, Arrays, and Matrices
Vectors and scalars are special cases of a matrix—all of which are represented
as arrays in MATLAB. A scalar is an array of 1 × 1 dimension, whereas a row
vector is an array of 1 × n dimension, and a column vector is an array of n × 1
dimension. When elements of an array are typed in a row within square brackets,
with a space between the elements, MATLAB displays it as a row vector. For
example, when you type
>>A=[120315]
it displays
A=120315
If the array is typed without assigning a name for the array,
>>[120315]
,
MATLAB responds with
ans=1 2 0 3 1 5
When you type elements with a semicolon between them, the elements are dis-
played in a column vector, for example
>>B=[1 2 0; 3 1 5; 0 4 -2] displays the 3 -by-3 matrix
B= 1 2 0
31 5
04-2
If a semicolumn is entered at the end of an array or a command, then the
array and the output of the command is not displayed on the command window,
but the command as well as the output variables are saved in a buffer known
as the workspace. The workspace saves the variables, data, contents of arrays
and matrices, and other elements as well as a record of the commands typed
by the user. It is recommended that at the beginning of the session, you change

INTRODUCTION
393
the directory to the disk drive
a:
if you have one in your computer so that the
contents of the workspace are saved in the floppy disk in that drive. Instead of
using the semicolumn between the elements, you can type the element on the
next line or by leaving one space, type three dots at the end of the line and
continue on the next line as shown below; this is useful when the array is very
long and extends beyond the end of the line:
>>C=[1 2 0
315
0 4 -2]
or
>>C=[ 1 2 0;315;...
0 4 -2]
displays the answer
C=1 2 0
31 5
04-2
9.1.2 Matrix Operations
It is now obvious that a column vector can be created by typing the elements
with a semicolumn separating them or creating a row vector and transposing
it. In MATLAB, the transpose of a matrix or a vector is carried out by the
operator, that is, the command
x’
gives the transpose of the vector or matrix
x
.
Since the vectors and matrices listed and described above have been saved in the

workspace, if we type
>>A’
,weget
ans
1
2
0
3
1
5
and
>>D=C’
yields
D=
130
214
05-2
If we type
C(:)
, we get a column vector with the columns of C arranged in
a vertical vector:
ans =
1
394
MATLAB PRIMER
3
0
2
1
4

0
5
-2
When a scalar, vector, or matrix is multiplied (or divided) by a scalar c,every
element of the scalar, vector or matrix is multiplied (or divided) by c.When
c is added to matrix, it is added to every element of the vector or matrix. For
example,
x=5
;
F=x*C
gives the output
F=5100
15525
0 20 -10
FF=x+C gives the output as
FF=67 5
8610
59 3
Addition and subtraction of two matrices (and vectors) is carried out by
MATLAB, according to the rules of matrix algebra, when they have the same
dimension. Multiplication of a vector or matrix by a vector or matrix is carried
out according to the rules of algebra when they are compatible or commensu-
rate for multiplication. The matrix operations and their corresponding notations
available in MATLAB are given below:
Addition
+
Subtraction
-
Multiplication
*

Power or exponent
^
Transpose

Left division
\
Right division
/
Note that the command
x=M\b
gives us the solution to the equation
M*x=b
,
where
M
is a square matrix that is assumed to be nonsingular. In matrix algebra,
the solution is given by x = M
−1
b. The left division is a more commonly used
operation in application of matrix algebra. (The command for the right division
x=b/M
gives the solution to the equation
x*M=b
, assuming that x and M are
compatible for multiplication and the solution in matrix algebra is given by
x=bM
−1
.)
INTRODUCTION
395

When we use the same variables used above but define them with new values,
they become the current values for the variables, so we define and use them
below as examples of the operations described above:
>>A=[1 2 1;0 1 1;2 1 1];
>>B=[2 1 0;1 1 1;-1 2 1];
>>C=A+B
C=
331
122
132
>>D=A*B
D=
353
032
452
>>M=A;
>>b=[2;4;4];
>>x=M\b
x = 0.0000 -2.0000 6.0000
Whereas the addition and subtraction of matrices are carried out by the addition
and subtraction term by term from the corresponding positions of the elements,
we know that the multiplication and “division” of matrices follow different rules.
MATLAB gives the correct answer in all the preceding operations. It has another
type of operation that is carried out when we use a dot before the sign for the
mathematical operation between the two matrices. The multiplication
(.*)
, divi-
sion
(./)
, and exponentiation

(.^)
of the terms in the corresponding positions
of the two compatible matrices are the three array operations.
Instead of multiplying the two matrices as
D=A*B
, now we type a dot before
the sign for multiplication. For example, the answer to
>>D=A.*B
is
D=
220
011
-221
It is easy to see the result of the command
>>A
^2
= A ∗ A
as
ans =
354
222
464
Let us define a matrix
X=

12
34

396
MATLAB PRIMER

Now we compute
U=X.^2
and
V=2.^X
and get the following outputs:
>>U=X.^2
U=

1
2
2
2
3
2
4
2

>>V=2.^X:
V=

2
1
2
2
2
3
2
4

A matrix can be expanded by adding new matrices and column or row vectors

as illustrated by the following examples:
>>F=[A B]
F=
121210
011111
211-121
>>b=[5 4 2];
>>G=[A;B;b]
G=
121
011
211
210
111
-1 2 1
542
The division operator
./
can be used to divide a scalar by each of the matrix
element as shown below, provided there are no zeros in the matrix:
>>W = 12./X produces the result
W= 12 6
43
>> WW= [6 2; 2 3];
W./WW
divides the elements of W by the elements of WW term by term:
ans=2 3
21
The element in the
(i,j)

position of a matrix
G
is identified by typ-
ing
>>G(7,2)
, and we get
ans=4
, and we can change its value by typing
>>G(7,2)=6
, so that now we have
INTRODUCTION
397
G=
121
011
211
210
111
-1 2 1
562
The colon sign
:
can be used to extract a submatrix from a matrix as shown by
the following examples:
>>Q=



256
324

−318



>>Q(:,2)
gives a submatrix with elements in all rows and the second column only:
ans =
5
2
1
The command
Q(3,:)
gives the elements in all columns and the third row only:
ans =
-3 1 8
The command
Q(1:2,2:3)
gives the elements in the rows from 1 to 2 and in
the columns from 2 to 3:
ans =
56
24
There are many other operations that can be applied on a matrix, such as
A
,
as listed below:
MATRIX OPERATIONS
rot90(A)
Rotates the matrix array by 90


fliplr(A)
Flips the columns left to right
flipud(A)
Flips the rows up to down
triu(A)
Gives the upper triangular part of the matrix
tril(A)
Gives the lower triangular part of the matrix
There are a few special matrices; we will list only three that are often found
useful in manipulating matrices:
ones(m,n)
, which gives a matrix with the number one in all its m rows and
n columns
398
MATLAB PRIMER
zeros(m,n)
, which gives a matrix with zeros in all its m rows and n columns
eye(m)
, which gives the “identity matrix” of order m × m.
We note that the inverse of a matrix
A
is obtained from the function
inv(A)
,
the determinant of a matrix
A
is obtained from the function
det(A)
and the rank
from

rank(A)
.
Since this is only a primer on MATLAB, it does not contain all the information
on its functions. You should refer to the user’s guide that accompanies every
software program mentioned above or any other books on MATLAB [1–3]. When
you have logged on to MATLAB or any of the subdirectories for the toolboxes,
there is an online help readily available. You type
help functionname
,where
functionname
is the name of the function on which detailed information is
desired, and immediately that information is displayed on the command window.
So there is no need to memorize the syntax and various features of the function
and so on. The best way to learn the use of MATLAB and the toolboxes is to
try the functions on the computer, using the
help
utility if necessary.
9.1.3 Scalar Operations
If t = (0.1π) radians per second, the MATLAB function
sin(t)
gives the answer
as 0.3090. To compute and plot
v = sin(0.1πt)
, in the time interval [0 2π]
we have to choose discrete values for the continuous variable t and compute
v
at these values. To do so, we create an array
t=[0.0:0.1:2.0]
; this gives the
sequence of 21 values within t = 0.0–2.0 in increments of 0.1. Now if we type

the function
v=sin(pi*t)
, the result is a sequence of 21 values. The command
stem(v)
immediately plots these values for
v
in a “graphics window” as shown
in Figure 9.1.
We have used the command
figure
to create a new window and the command
plot(t,v)
to get the plot as a continuous plot joining the discrete values of
v
(see Fig. 9.2). If we did not use the command
figure
, the second figure would
replace the first one on the graphics window. Typing the command
grid
on the
command window results in the plots having grid lines shown in these figures.
Next we use the commands for adding a title and the labels for the y and x
coordinates with the commands
title, ylabel
,and
xlabel
.
So the commands entered on the command window to get the two figures are as
follows. Since MATLAB chooses the scales for the x and y coordinates, depend-
ing on the range of their values, we may have to change the literal arguments in

the
ylabel
and
xlabel
:
t = [0.0:0.1:2.0];
v=sin(pi*t);
stem(v);grid
title(’Values of sin(pi*t)’)
ylabel(’Values of sin(pi*t)’)
xlabel(’Values of 10t’)
figure
INTRODUCTION
399
1
0.8
0.6
0.4
0.2
0
−0.2
−0.4
−0.6
−0.8
−1
0
510
15
20 25
Values of sin (pi


t)
Plot of sin (pi

t)
Values of 10t
Figure 9.1 Plot of sin(
pi*nT)
.
1
Plot of sin (pi

t)
0.8
0.6
0.4
0.2
Values of sin (pi

t)
0
−0.2
−0.4
−0.6
−0.8
−1
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8
2
Values of 10t
Figure 9.2 Plot of sin(

pi*t
).
plot(t,v);grid
title(’Plot of sin(pi*t)’)
ylabel(’Value of sin(pi*t)’)
xlabel(’Value of t’)
400
MATLAB PRIMER
9.1.4 Drawing Plots
Additional arguments can be added in the command
plot(t,v)
to specify the
color of the curve; for example,
plot(t,v,’g’)
will show the curve in green
color. The arguments for other colors are as follows:
y
yellow
m
magenta
c
cyan
r
red
b
blue
w
white
k
black

The next argument that can be added is a marker used to draw the curve. For
example,
plot(t,v,’g’,’+’)
will plot the curve with the + sign instead of
the line curve, which is the default marker. Other markers that are available are
o
circle
.
point
*
star
-
solid line
:
dotted line
--
dashed line
-.-
dash–dot–dash
One can plot several curves in the same figure; for example, we can plot both
v and y versus t by the command
plot(t,v,’g’,’-’t,y,’r’,’*’)
. Another
way of plotting more than one variable in the same figure is to use the command
hold on
after plotting the first variable and then typing the command for plotting
the second variable:
plot(t,v,’g’);
hold on
plot(t,y,’r’)

The use of the MATLAB commands
subplot grid
,and
axis
have been
described and used earlier in the book. The commands
gtext
and
ginput
are
also very useful in plotting. There is a tool called
fvtool
(filter visualization
tool) in the more recent versions of the Signal Processing Toolbox, which offers
several other features in plotting the response of digital filters. You may type
help
gtext
,
help ginput
,or
help fvtool
to get more information about them.
9.1.5 MATLAB Functions
The other functions, in addition to
sin
, that are available in MATLAB are given
below:
INTRODUCTION
401
TRIGONOMETRIC FUNCTIONS

sin
sine
cos
cosine
tan
tangent
asin
arcsine
acos
arccosine
atan
arctangent
atan2
four-quadrant arctangent
sinh
hyperbolic sine
cosh
hyperbolic cosine
tanh
hyperbolic tangent
asinh
hyperbolic arcsine
acosh
hyperbolic arccosine
atanh
hyperbolic arctangent
MATHEMATICAL FUNCTIONS
abs
absolute value or magnitude
angle

phase angle of a complex number
sqrt
square root
real
real part of a complex number
imag
imaginary part
conj
complex conjugate
round
round toward nearest integer
fix
round toward zero
floor
round toward −∞
ceil
round toward ∞
sign
signum function
rem
remainder
exp
exponential base 2
log
natural logarithm
log10
log base 10
9.1.6 Numerical Format
We can specify the format in which MATLAB displays numbers. If the num-
ber is an integer, then by default, it is displayed as an integer. If it is a real

number, it is displayed with approximately four digits to the right of the dec-
imal point (e.g., 12.0945), and this is the default format
format short
.If
the number has many more significant digits, we specify other formats, using
the scientific notation. For example, let the number be 12.094567832155321.
If we type the MATLAB command
format long
, this number will be dis-
played with 16 digits as 12.09456783215532. If we declare the
format short
e
, the number will be displayed with five digits and an exponent in the form
1.2094e+01, whereas the command
format long e
selects 16 digits and an
exponent: 1.209456783215532e+01.
Remember that these formats are used for display on the monitor, the result
of commands, functions, and operations. But the numerical computations that
implement the functions and scripts are done by MATLAB with a higher degree
402
MATLAB PRIMER
of precision if and when it is necessary, for example, when we use the functions
and scripts in the Signal Processing Toolbox.
9.1.7 Control Flow
Three functions are used to control the flow of command execution that depend
on decisionmaking statements. Such functions are found in other programming
languages and also in MATLAB. They are
for loops
,

If-elseif-end loops
and
while loops
, which will be illustrated below.
The statement
>> for n=1:10
x(n )=n^2+4*n
end
produces a vector containing 10 values of x(n) = n
2
+ 4n,forn = 1, 2, 3,...,10.
Onecandefineanarraysuchas
n=3:-0.5:-1.0
, in which the increment
is −0.5 and the result is an array
n = [3.0 2.5 2.0 1.5 1.0 0.5 0.0
-0.5 -1.0]
. The default value for the increment is 1.
To define a two-dimensional array, and a function
H(i,j)=0.1^i+0.2^j
,we
use the statements
for i =1:20;
for j =1:20;
X(i,j) = 0.1^i+0.2^j
end
end
An example of the use of the
if
statement is

>>n=-10:10
if n<0
x(n)=0;
elseif 0≤n≤5;
x(n)=(0.8).^n;
else
x(n)=0
end
Note that an error message will be shown if we use the statement
x(n) = (0.8)^n
without the dot before the exponent.
The
while
loop is executed step by step as long as the relation holds true.
An example of this is
>>n=1
while n<8
x(n)=0.5^n;
n=n+1
end
INTRODUCTION
403
If the values of x(n)whenn takes the maximum value of 7 is desired, we
type
x
after the
end
statement and get the result
0.5000 0.2500 0.1250 0.0625 0.0313 0.0156 0.0078
But this problem is solved more easily by the following two statements to get

the same values for x(n), n = 1, 2, 3,...,7, but we have to insert a dot before
the exponent (
^
)sincen is a row vector of seven elements. It is very helpful to
find the order of a matrix or a vector A by using the statement
S= size(A)
to
know when to use the dot for the term-by-term operation—particularly when we
get an error message about the dimensions of the matrices:
>>n=1:7;
x(n)=(0.5).^n
9.1.8 Edit Window and M-file
So far we have introduced a few of the common functions and operations of
MATLAB that are used in the command window and the graphics window.
When we are in the command window, we are in an interactive mode, where each
command is executed immediately after it is typed and the answer is displayed. If
we wish to make a change in any one of the previous statements or the input data,
we have to trace it back one line at a time using the

key and edit the line, then
use the

key to get to the line where we had stopped. If that statement is very
many lines before the current line or if we want to make major changes in the
program, or if we wish to find the output of the program for different values for
the input parameters, this is not a convenient procedure. So we create a program
or a script by clicking
File-Open-New-M-file
and use a text editor that is
built-in MATLAB or any other text editor and save it in the current directory

asafilewithanameandan
.m
extension. We can write this script using the
MATLAB functions and operations; we can even use other functions or functions
that we have written. Such a file is called an M-file, and after it is saved, we click
the command window and type just the name of the M-file without the extension.
The entire script is executed if there are no bugs in it and the results displayed. If
there are any error messages, we go back to M-file in the edit window and make
corrections, save it, get back to the command window, and then type the name
of the M-file to run it again. Either we enter the values of the input variable(s)
in the M-file or add the following command in the M-file:
input(’Type in the input parameters for xyz’)
When the script is to be executed, the program displays the statement
Type in
the input parameters for xyz
and waits for the input from the keyboard.
We may have requests for input for several parameters, and when the data for
all the parameters are entered by us from the keyboard, the program is executed.

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×