You are on page 1of 35

MATLAB

MATLAB WORKSHOP
WORKSHOP

FOR EE 327
MWF 8:00-850 AM
August 26-30, 2002

Dr. Ali A. Jalali

MATLAB
MATLAB WORKSHOP
WORKSHOP
WORKSHOP
WebPages
www.csee.wvu.edu/~jalali

CLS-MATLAB
CLS-MATLAB Files
Files
Textbook
Textbook MATLAB
MATLAB Files
Files for
for Download
Download ::
http://www.csee.wvu.edu/~jalali
http://www.csee.wvu.edu/~jalali
http://www.brookscole.com/engineering/ee/bookware.html
http://www.brookscole.com/engineering/ee/bookware.html

Macintosh
Macintoshand
andMS-Windows
MS-WindowsVersions
Versions
AA For
Answers
For
Answersof
ofproblems
problems
EE For
Examples
For
Examples
FF For
Figures
For
Figures
PP For
Problems
For
Problems
Follows
Followsby
byaaone
oneor
ortwo-digit
two-digitnumber
number11through
through11
11corresponding
correspondingto
to
the
chapter.
the chapter.
The
Thefinal
finalcharacters
charactersindicate
indicatethe
thenumber
numberof
ofthe
theappropriate
appropriateanswer.
answer.
(A8_16)
Answer
(A8_16)
Answerfor
forproblem
problem16
16Chapter
Chapter88
(E7_4)
Example
Filter outputs using convolution)
(E7_4)
Example44in
inchapter
chapter77 (%E7_4
(%E7_4 Filter outputs using convolution)
(F4_2)
Figure
(F4_2)
Figure44in
inChapter
Chapter22
(P8_20)
Problem
(P8_20)
Problem20
20in
inChapter
Chapter88

Unit Step Function (Figure 1.7a text)


%F1_7a
%F1_7a Unit
Unit step
step function
function
t=-2:0.01:5;
%% make
t=-2:0.01:5;
make tt aa
vector
of
701
points
vector of 701 points
q=size(t);
q=size(t);
f=zeros(q(1),q(2));
f=zeros(q(1),q(2)); %% set
set ff ==
a vector of zeros
a vector of zeros
q=size(t(201:701));
q=size(t(201:701));
f(201:701)=ones(q(1),q(2));%
f(201:701)=ones(q(1),q(2));%
set
set final
final 500
500 points
points of
of ff to
to 11
plot(t,f),title('Fig.1.7a
Unit
plot(t,f),title('Fig.1.7a Unit
step
step function');
function');
axis([-2,5,-1,2]);
axis([-2,5,-1,2]); %% sets
sets
limits on axes
limits on axes
xlabel('time,
xlabel('time, t');
t');
ylabel('
u(t)');
ylabel(' u(t)');
grid;
grid;

B if
Bu (t t0 )
0 if

Generic step
function

t t0
t to .

EE 327 fall 2002

%F1_7b Signal g(t) multiplied f(101:501)=2.5cos(5*t(101:501) by a pulse functions ([u(t+1)-u(t-3)]


%F1_7b
%F1_7b Signal
Signal g(t)
g(t) multiplied
multiplied by
by aa pulse
pulse functions
functions
t=
t= -2:0.01:5;
-2:0.01:5;
q=size(t);
q=size(t);
f=zeros(q(1),q(2));
f=zeros(q(1),q(2));
f(101:501)=2.5-cos(5*t(101:501));
f(101:501)=2.5-cos(5*t(101:501));
plot(t,f),title('Fig.1.7b
plot(t,f),title('Fig.1.7b Signal
Signal g(t)
g(t) multiplied
multiplied by
by
aa pulse
pulse functions');
functions');
axis([-2,5,-1,4]);
axis([-2,5,-1,4]);
xlabel('time,
xlabel('time, t');
t');
ylabel('
ylabel(' g(t)[u(t+1)-u(t-3)]');
g(t)[u(t+1)-u(t-3)]');
grid;
grid;

EE 327 fall 2002

%F1_7b Signal g(t) multiplied by a pulse functions

EE 327 fall 2002

Sequences
1. Ramp Sequence
2.
3.

A shifted ramp sequence with slop of B is defined by: g (n) B(n n0 )


The unit ramp sequence and shifted ramp sequences

4.

Example: g(t) = 2(n-10).

MATLAB
MATLABCode:
Code:
n=-10:1:20;
n=-10:1:20;
f=2*(n-10);
f=2*(n-10);
stem(n,f);
stem(n,f);

EE 327 fall 2002

Real Exponential Sequences


1. Real exponential sequence is defined as:

f (n) A(a) n

Example for A = 10 and a = 0.9, as n goes to infinity the sequence


approaches zero and as n goes to minus infinity the sequence
approaches plus infinity.
Composite sequence:

p(n) A(a ) n u (n)


Multiplying point by
Point by the step sequence

MATLAB Code:
n=-10:1:10;
f =10*(.9).^n;
stem(n,f);
axis([-10 10 0 30]);

EE 327 fall 2002

Sinusoidal Sequence
1. A sinusoidal sequence may be described as:

2n

f (n) A cos

N

2.

Where A is positve real number (amplitude), N is the period, and a


is the phase.
3. Example:
4. A = 5, N = 16
5. And

a / 4.

6. MATLAB Code:
7.
8.
9.

n=-20:1:20;
f=5*[cos(n*pi/8+pi/4)];
stem(n,f);

EE 327 fall 2002

Exponentially Modulated Sinusoidal Sequence


1. By multiplying an exponential sequence by sinusoidal sequence, we
obtain an exponentially modulated sequence described by:

2. Example:
3. A = 10, N = 16, a = 0.9

/ 4.

1. MATLAB Code:
2.
3.
4.
5.
6.
7.

n=-20:1:20;
f=10*[0.9 .^n];
g=[cos(2*n*pi/16+pi/4)];
h=f .*g;
stem(n,h);
axis([-20 20 -30 70]);

EE 327 fall 2002

2n

g (n) A(a ) n cos



N

MATLAB
MATLAB WORKSHOP
WORKSHOP
Lecture # 1

Monday August 26
Introduction
MATLAB Demos

MATLAB Basics

Lecture # 2
Wednesday August 28

MATLAB Basics

MATLAB Plots

MATLAB Examples

Lecture # 3
Friday August 30

MATLAB Fundation

Textbook Examples

Short Quiz

MATLAB
MATLAB WORKSHOP
WORKSHOP

Lecture # 2
Wednesday August 28
MATLAB Basics
MATLAB Plots
MATLAB Examples

MATLAB
MATLAB Basics
Basics
Contents
Contents

Numbers
Numbers and
and Format
Format
Command
Command Line
Line Help
Help
Variables
Variables
Vectors
Vectors and
and Matrices
Matrices
Plotting
Plotting Elementary
Elementary Functions
Functions
Loading
Loading and
and Saving
Saving
M-Files
M-Files
Loops
Loops and
and If
If Statements
Statements
User
User Defined
Defined Variable
Variable

MATLAB
MATLAB Basics
Basics
Numbers
Numbers and
and Format:
Format:

MATLAB
MATLABrecognizes
recognizesseveral
severaldifferent
differentkinds
kindsof
ofnumbers:
numbers:

Integer
Integer (like:
(like:12
12--678),
678),
Real
(like:
Real
(like:4.607
4.607--199.34),
199.34),
Complex
Complex(like:
(like:22++3i
3i,,i=j=sqrt(-1)),
i=j=sqrt(-1)),
Inf
(like:
Inf
(like:Infinity
Infinity2/0),
2/0),
NaN
(like:
NaN
(like:Not
NotaaNumber,
Number,0/0).
0/0).

All
All computations
computations in
in MATLAB
MATLAB are
are done
done in
in
double
double precision,
precision, which
which means
means about
about 15
15
significant
significant figures.
figures.

MATLAB
MATLAB Basics
Basics
Numbers
Numbers and
and Format:
Format:
The
Theformat
format command
commandin
inMATLAB
MATLABis
is used
usedto
tocontrol
control
pints
pintsnumbers.
numbers.
The
Thenumber
numberof
of digits
digitsdisplayed
displayedis
isnot
not related
relatedto
tothe
the
accuracy.
accuracy.
To
Tochange
changethe
theformat
formatof
ofthe
thedisplay,
display,type
type
format
format short
short eefor
forscientific
scientific notation
notationwith
with55 decimal
decimal
places,
places,
format
formatlong
longee for
for scientific
scientificnotation
notationwith
with 15
15
significant
significant decimal
decimalplaces
placesand
and
format
formatbank
bank for
forplacing
placing two
twosignificant
significant digits
digits to
to the
the
right
right of
of the
thedecimal.
decimal.

MATLAB
MATLAB Basics
Basics
Numbers
Numbers and
and Format:
Format:
Use
Use help
help format
format for
for more
more information.
information.

Command
Command

format
format short
short
format
format short
short ee
format
format long
long ee
format
format bank
bank
format
format hex
hex
format
format ++

Example
Example of
of Output
Output

11.3045
11.3045 (4-decimal
(4-decimal Places)
Places)
1.1304e+01
1.1304e+01
1.130452467450893+01
1.130452467450893+01
11.30
11.30 (2-decimal
(2-decimal places)
places)
Hexadecimal
Hexadecimal format
format
The
The symbols
symbols of
of +,
+, -- and
and
blank
blank are
are printed
printed

MATLAB
MATLAB Basics
Basics
Command
Command Line
Line Help:
Help:
Help
Help and
and information
information on
on MATLAB
MATLAB can
can be
be
found
found in
in several
several ways,
ways,
from
from the
the command
command line
line by
by using
using the
the 'help'
'help'
topic
topic command
command
from
from the
the separate
separate Help
Help window
window found
found
under
under the
the Help
Help menu
menu
from
from the
the MATLAB
MATLAB helpdesk
helpdesk stored
stored on
on disk
disk
or
or on
on aa CD-ROM
CD-ROM

MATLAB
MATLAB Basics
Basics
Command
Command Line
Line Help:
Help:
>>help
>>help pi
pi
PI
PI 3.1415926535897....
3.1415926535897....
PI
PI == 4*atan(1)
4*atan(1) == imag(log(-1))
imag(log(-1)) ==
3.1415926535897....
3.1415926535897....
>>help
>>help sin
sin
SIN
SIN Sine.
Sine.
SIN(X)
SIN(X) is
is the
the sine
sine of
of the
the elements
elements of
of X.
X.

MATLAB
MATLAB Basics
Basics
Variables:
Variables:

Variables
Variables ans
ansis
is assigned
assignedby
byMATLAB
MATLABdefault.
default.
For
Forexample,
example,typing
typing >>12+2.3*2
>>12+2.3*2 or
or >>12+2.3*2,
>>12+2.3*2,
yields:
yields: ans
ans== 16.6000
16.6000
>>12+2.3*2;
>>12+2.3*2; yields:
yields: blank
blank
(but
(butthe
theresult
result is
issaved
savedon
onthe
thevariable
variable"ans"
"ans"
(write
(write >>ans
>>anssee
seethe
theresult
resultof
ofoperation
operation which
which is
is
16.6000).
16.6000).
Commas
Commas(,)
(,) tell
tellMATLAB
MATLABto
todisplay
displayresults
results
semicolons
semicolons(;(; ))suppress
suppressprinting.
printing.

MATLAB
MATLAB Basics
Basics
Variables:
Variables:

Variables
Variablesare
areassigned
assignednumerical
numerical values
valuesby
bytyping
typing
the
theexpression
expression directly,
directly,for
for example,
example, typing
typing
>>a
>>a==12+2.3*2
12+2.3*2
yields:
yields: aa==16.6000
16.6000
The
Theanswer
answerwill
willnot
not be
bedisplayed
displayedwhen
whenaasemicolon
semicolon
is
isput
putat
atthe
theend
endof
ofan
anexpression,
expression, for
forexample
exampletype
type
>>a
>>a==12+2.3*2;
12+2.3*2;

MATLAB
MATLAB Basics
Basics
Variables:
Variables:

Legal
Legalvariable
variablenames
namesconsist
consist of
of any
anycombination
combination
of
ofletters
lettersand
anddigits,
digits,starting
startingwith
withaa letter.
letter.
Examples:
Examples: Ali22B,
Ali22B, Cost,
Cost, X3_f22
X3_f22 and
and s2Sc6
s2Sc6..
But
Butthe
thevariables
variableslike:
like:

Ali-22,
Ali-22, 5x,
5x, 3Cost,
3Cost, &r5,
&r5, %67
%67 and
and @xyt56
@xyt56
are
arenot
notallowed
allowedin
inMATLAB.
MATLAB.
Characters
Characters in
inMATLAB
MATLABis
islike
likeX='a';
X='a';
Strings
Strings in
inMATLAB
MATLABis
islike
likemg1='Ali';
mg1='Ali'; or
or
mg2='MATLAB
mg2='MATLABDEMOS';
DEMOS';

MATLAB
MATLAB Basics
Basics
Variables:
Variables:
MATLAB
MATLAB utilizes
utilizes the
the following
following arithmetic
arithmetic
operators:
operators: The
The following
following matrix
matrix and
and array
array
operations
operations are
are available
available in
in MATLAB:
MATLAB:
++ for
for addition
addition
-- for
for subtraction
subtraction
** for
for multiplication
multiplication
^^ for
for power
power
for
for transpose
transpose
\\ for
for left
left division
division
// for
for right
right division
division

MATLAB
MATLAB Basics
Basics
Variables:
Variables:
These
These matrix
matrix operations
operations apply
apply to
to scalars
scalars
(1-by-1
(1-by-1 matrices)
matrices) as
as well.
well.
Comment
Comment statements
statements are
are preceded
preceded by
by aa
""%
%".".
The
The commands
commands who
who and
and whose
whose give
give the
the
names
names of
of the
the variables
variables that
that have
have been
been
defined
defined in
in the
the workspace.
workspace.

MATLAB
MATLAB Basics
Basics
Variables:
Variables:
AAvariable
variable can
can be
beassigned
assigned using
using aaformula
formulathat
that
utilizes
utilizesthese
theseoperators
operatorsand
andeither
eithernumbers
numbersor
or
previously
previouslydefined
definedvariables.
variables.
For
Forexample,
example,since
since aawas
wasdefined
defined previously,
previously,the
the
following
followingexpression
expressionis
isvalid
valid
>>b
>>b== 5*a;
5*a;
To
Todetermine
determinethe
the value
valueof
ofaa previously
previouslydefined
defined
quantity,
quantity,type
typethe
thequantity
quantityby
byitself:
itself:
>>b
>>b
yields:
yields: bb== 83.0000
83.0000

MATLAB
MATLAB Basics
Basics
Variables:
Variables:

IfIfyour
yourexpression
expressiondoes
doesnot
not fit
fit on
onone
oneline,
line,use
usean
an
ellipsis
ellipsis(three
(threeor
or more
moreperiods
periodsat
atthe
the end
end of
of the
the
line)
line)and
andcontinue
continueon
onthe
thenext
next line.
line.
>>c
>>c==1+2+3+...
1+2+3+...
5+6+7;
5+6+7;
There
Thereare
areseveral
several predefined
predefinedvariables
variables which
which can
can
be
beused
usedat
at any
anytime,
time,in
inthe
thesame
samemanner
manneras
asuseruserdefined
definedvariables:
variables:
i,i, sqrt(-1)
sqrt(-1) -- j,j, sqrt(-1)
sqrt(-1) -- pi,
pi, 3.1416...
3.1416...

MATLAB
MATLAB Basics
Basics

Variables:
Variables:

There
Thereare
arealso
alsoaanumber
numberof
of predefined
predefinedfunctions
functions
that
thatcan
canbe
beused
usedwhen
whendefining
defining aavariable.
variable. Some
Some
common
commonfunctions
functionsthat
thatare
areused
usedin
inthis
thisworkshop
workshop
are:
are:
abs
magnitude
abs
magnitudeof
of aanumber
number (absolute
(absolutevalue
valuefor
for
real
realnumbers)
numbers)
angle
angle angle
angleof
of aacomplex
complex number,
number,in
inradians
radians
cos
cosine
cos
cosinefunction,
function,assumes
assumesargument
argument is
isin
in
radians
radians
sin
sin
sin
sinfunction,
function,assumes
assumesargument
argumentis
isin
in
radians
radians
exp
exponential
exp
exponential function
function

MATLAB
MATLAB Basics
Basics
Variables:
Variables:

For
Forexample,
example,with
withyydefined
definedas
asabove,
above,
xx==abs(y)
abs(y)
yields:
yields:xx==10.8167
10.8167
cc==angle(y)
angle(y)
yields:
yields:xx==0.9828
0.9828
With
Withaa==33as
asdefined
definedpreviously,
previously,
xx==cos(a)
cos(a)
yields:
yields:cc==--0.9900
0.9900
xx==exp(a)
exp(a)
yields:
yields:xx==--20.0855
20.0855
Note
Notethat
thatexp
expcan
canbe
beused
usedon
oncomplex
complexnumbers.
numbers.For
Forexample,
example,with
with
yy==2+8i
as
defined
above,
2+8i as defined above,
xx==exp(y)
exp(y)
yields:
yields:xx==--1.0751
1.0751++7.3104i
7.3104i
which
whichcan
canbe
beverified
verifiedby
byusing
usingEuler's
Euler'sformula:
formula:

xx==exp(2)cos(8)
exp(2)cos(8)++j.exp(2)sin(8)
j.exp(2)sin(8)

MATLAB
MATLAB Basics
Basics
Vectors
Vectors and
and Matrices:
Matrices:

MATLAB
MATLABis
isbased
basedon
on matrix
matrix and
and vector
vectoralgebra;
algebra;
even
evenscalars
scalarsare
aretreated
treatedas
as11by
by11matrices.
matrices.
Therefore,
Therefore,vector
vectorand
andmatrix
matrixoperations
operationsare
areas
as
simple
simpleas
ascommon
commoncalculator
calculatoroperations.
operations.
The
Thenumber
numberof
ofentries
entries(elements
(elements or
or components)
components)
is
isknown
knownas
asthe
the"length"
"length"of
ofthe
thevector.
vector.

The
The entries
entries must
must be
be enclosed
enclosed
in
in square
square brackets.
brackets.

MATLAB
MATLAB Basics
Basics
Vectors
Vectors and
and Matrices:
Matrices:

Vectors
Vectorscan
canbe
bedefined
definedin
intwo
twoways.
ways.
The
Thefirst
firstmethod
methodis
isused
usedfor
forarbitrary
arbitraryelements:
elements:
>>v
>>v==[1
[13355sqrt(49)];
sqrt(49)];
creates
createsaa1x4
1x4vector
vectorwith
withelements
elements1,
1,3,
3,55and
and7.
7.
Note
Notethat
thatcommas
commascould
couldhave
havebeen
beenused
usedin
inplace
placeof
ofspaces
spaces
to
separate
the
elements
([1,3,5,sqrt(49)]).
to separate the elements ([1,3,5,sqrt(49)]).
Additional
Additionalelements
elementscan
canbe
beadded
addedto
tothe
thevector:
vector:
>>v(5)
>>v(5)==8;
8;
yields
yieldsthe
thevector
vectorvv==[1
[13355778].
8].
Previously
Previouslydefined
definedvectors
vectorscan
canbe
beused
usedto
todefine
defineaanew
new
vector.
vector.
For
Forexample,
example,with
withvvdefined
definedabove
above
>>a
>>a==[9
[910];
10];
>>b
>>b==[v
[va];
a];
creates
createsthe
thevector
vectorbb==[1
[1335577889910].
10].

MATLAB
MATLAB Basics
Basics
Vectors
Vectors and
and Matrices:
Matrices:

The
Thesecond
secondmethod
method is
is used
used for
for creating
creatingvectors
vectors
with
withequally
equallyspaced
spaced elements:
elements:
>>t
>>t == 0:0.1:10;
0:0.1:10;
creates
createsaa1x101
1x101vector
vectorwith
withthe
theelements
elements0,
0, .1,
.1, .2,
.2,..
3,...,10.
3,...,10.
Note
Notethat
thatthe
themiddle
middlenumber
numberdefines
definesthe
the
increment.
increment.
IfIfonly
onlytwo
twonumbers
numbersare
aregiven,
given,then
thenthe
theincrement
increment
is
isset
setto
toaadefault
default of
of 1:
1:
>>k
>>k==0:10;
0:10;
creates
createsaa1x11
1x11vector
vectorwith
withthe
theelements
elements0,
0,1,
1, 2,
2,...,
...,
10.
10.

MATLAB
MATLAB Basics
Basics
Vectors
Vectors and
and Matrices:
Matrices:
Matrices
Matrices are
are defined
defined by
by entering
entering the
the
elements
elements row
row by
by row:
row:
>>A
>>A== [2
[2 33 4;
4; 55 -7
-7 6;
6; 10
10 55 3]
3]
creates
creates the
the matrix
matrix

MATLAB
MATLAB Basics
Basics
Vectors
Vectors and
and Matrices:
Matrices:
There
There are
are aa number
number of
of special
special matrices
matrices that
that
can
can be
be defined:
defined:
null
M
null matrix:
matrix:
M == [[ ];];
nxm
nxm matrix
matrix of
of zeros:
zeros: M
M == zeros(n,m);
zeros(n,m);
nxm
nxm matrix
matrix of
of ones:
ones: M
M == ones(n,m);
ones(n,m);
nxn
nxn identity
identity matrix:
matrix: M
M == eye(n);
eye(n);

MATLAB
MATLAB Basics
Basics
Vectors
Vectors and
and Matrices:
Matrices:

AAparticular
particularelement
elementof
ofaamatrix
matrixcan
canbe
beassigned:
assigned:
>>M(1,2)
>>M(1,2)==5;
5;
places
placesthe
thenumber
number55in
inthe
thefirst
firstrow,
row,second
secondcolumn.
column.
Operations
Operationsand
andfunctions
functionsthat
thatwere
weredefined
definedfor
forscalars
scalarsin
inthe
the
previous
section
can
also
be
used
on
vectors
and
matrices.
previous section can also be used on vectors and matrices.
For
Forexample,
example,
>>a
>>a==[1
[1223];
3];
>>b
>>b==[4
[4556];
6];
>>c
>>c==aa++bb
yields:
yields: cc==557799
Functions
Functionsare
areapplied
appliedelement
elementby
byelement.
element.
For
Forexample,
example,
>>t
>>t==0:10;
0:10;
>>x
>>x==cos(2*t);
cos(2*t);
creates
createsaavector
vectorxxwith
withelements
elementsequal
equalto
tocos(2t)
cos(2t)for
fortt==0,
0,1,
1,2,
2,...,
...,10.
10.

MATLAB
MATLAB Basics
Basics
Vectors
Vectors and
and Matrices:
Matrices:

Operations
Operationsthat
thatneed
needto
tobe
beperformed
performedelement-by-element
element-by-element
can
canbe
beaccomplished
accomplishedby
bypreceding
precedingthe
theoperation
operationby
byaa".".
".".
For
Forexample,
example,to
toobtain
obtainaavector
vectorxxthat
thatcontains
containsthe
theelements
elements
of
ofx(t)
x(t)==tcos(t)
tcos(t)at
atspecific
specificpoints
pointsin
intime,
time,you
youcannot
cannotsimply
simply
multiply
multiplythe
thevector
vectorttwith
withthe
thevector
vectorcos(t).
cos(t).
Instead
Insteadyou
youmultiply
multiplytheir
theirelements
elementstogether:
together:
>>t
>>t==0:10;
0:10;
>>x
>>x==t.*cos(t);
t.*cos(t);
The
Thecommand
commandlength(x)
length(x)returns
returnsthe
thelength
lengthof
ofaavector
vectorxxand
and
size(x)
size(x)returns
returnsthe
thedimension
dimensionof
ofthe
thematrix
matrixx.
x.

MATLAB
MATLAB WORKSHOP
WORKSHOP
End of Lecture # 2

MATLAB EE 327
Next

time

You might also like