MATLAB Workshop Lecture 2
MATLAB Workshop Lecture 2
MATLAB WORKSHOP
WORKSHOP
• FOR EE 327
• MWF 8:00-850 AM
• August 26-30, 2002
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
For Answers
Answersof ofproblems
problems
•• EE For
For Examples
Examples
•• FF For
For Figures
Figures
•• PP For
For Problems
Problems
•• Follows
Followsby byaaone
oneorortwo-digit
two-digitnumber
number11through
through11 11corresponding
corresponding
to the chapter.
to the chapter.
•• The
Thefinal
finalcharacters
charactersindicate
indicatethe
thenumber
numberof ofthe
theappropriate
appropriateanswer.answer.
•• (A8_16)
(A8_16) Answer
Answerfor
forproblem
problem1616Chapter
Chapter88
•• (E7_4)
(E7_4) Example
Example44in inchapter
chapter77 (%E7_4 Filter outputs using convolution)
(%E7_4 Filter outputs using convolution)
•• (F4_2)
(F4_2) Figure
Figure44in
inChapter
Chapter22
•• (P8_20)
(P8_20) Problem
Problem2020ininChapter
Chapter88
Unit Step Function (Figure 1.7a text)
%F1_7a Unit step function
%F1_7a Unit step function
t=-2:0.01:5; % make t a
t=-2:0.01:5; % make t a
vector of 701 points
vector of 701 points
q=size(t);
q=size(t);
f=zeros(q(1),q(2)); % set f =
f=zeros(q(1),q(2)); % set f =
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 final 500 points of f to 1
set final 500 points of f to 1
plot(t,f),title('Fig.1.7a Unit
plot(t,f),title('Fig.1.7a Unit
step function');
step function');
axis([-2,5,-1,2]); % sets
axis([-2,5,-1,2]); % sets
limits on axes
limits on axes
xlabel('time, t');
xlabel('time, t');
ylabel(' u(t)');
ylabel(' u(t)');
grid;
grid;
B if t t0
Bu (t t0 )
0 if t to .
Generic step
function
EE 327 fall 2002
%F1_7b Signal g(t) multiplied f(101:501)=2.5-
cos(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 functions');
pulse 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;
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);
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]);
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
Real (like:
(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
Inf (like:
(like:Infinity
Infinity2/0),
2/0),
•• NaN
NaN (like:
(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
formatcommand
commandin inMATLAB
MATLABis isused
usedtoto
control
control pints
pintsnumbers.
numbers.
The
Thenumber
numberof ofdigits
digitsdisplayed
displayedisisnot
notrelated
relatedtotothe
the
accuracy.
accuracy.
To
Tochange
changethetheformat
formatofofthe
thedisplay,
display, type
type
format
format short
shortee for
forscientific
scientificnotation
notationwith
with55decimal
decimal
places,
places,
format
formatlong
longee for
forscientific
scientificnotation
notationwith
with15
15
significant
significantdecimal
decimal places
placesand
and
format
formatbank
bank for
forplacing
placingtwo
twosignificant
significantdigits
digitsto
tothe
the
right
rightof
ofthe
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 Example
Exampleof
ofOutput
Output
•• format
format short
short 11.3045
11.3045 (4-decimal
(4-decimal Places)
Places)
•• format
format short
short ee 1.1304e+01
1.1304e+01
•• format
format long
long ee 1.130452467450893+01
1.130452467450893+01
•• format
format bank
bank 11.30
11.30 (2-decimal
(2-decimal places)
places)
•• format
format hex
hex Hexadecimal
Hexadecimal format
format
•• 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 pipi
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 isassigned
assignedbyby MATLAB
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
resultis issaved
savedon onthe
thevariable
variable"ans"
"ans"
•• (write
(write >>ans
>>anssee seethe
theresult
resultof
ofoperation
operationwhich
whichisis
16.6000).
16.6000).
•• Commas
Commas(,) (,)tell
tell MATLAB
MATLABto todisplay
displayresults
results
•• semicolons
semicolons(;(; ))suppress
suppressprinting.
printing.
MATLAB
MATLAB Basics
Basics
Variables:
Variables:
•• Variables
Variablesareareassigned
assignednumerical
numerical values
valuesby bytyping
typing
the
theexpression
expressiondirectly,
directly, for
forexample,
example, typing
typing
•• >>a
>>a==12+2.3*2
12+2.3*2
•• yields:
yields: aa==16.6000
16.6000
•• The
Theanswer
answerwill
will not
notbebedisplayed
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
Legal variable
variablenames
namesconsist
consistof
ofany
anycombination
combination
of
ofletters
lettersand
anddigits,
digits, starting
startingwith
withaaletter.
letter.
Examples: Ali22B,
Examples: 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
MATLABisislike
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) asas well.
well.
•• Comment
Comment statements
statements are
are preceded
preceded by by aa
""%
%".".
•• The commands who
The commands and whose
who and whose givegive the
the
names
names ofof 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
variablecancanbebeassigned
assignedusing
usingaaformula
formulathat
that
utilizes
utilizesthese
theseoperators
operatorsand
andeither
eithernumbers
numbersor or
previously
previouslydefined
definedvariables.
variables.
•• For
Forexample,
example, since
since aawas
wasdefined
definedpreviously,
previously, the
the
following
followingexpression
expressionisisvalid
valid
•• >>b
>>b== 5*a;
5*a;
•• To
Todetermine
determinethethevalue
valueofofaapreviously
previouslydefined
defined
quantity,
quantity, type
typethe
thequantity
quantitybybyitself:
itself:
•• >>b
>>b
•• yields:
yields: bb==83.0000
83.0000
MATLAB
MATLAB Basics
Basics
Variables:
Variables:
•• IfIfyour
yourexpression
expressiondoes doesnotnotfit
fiton
ononeoneline,
line, use
useanan
ellipsis
ellipsis(three
(threeorormore
moreperiods
periodsat atthe
theend
endofofthe
the
line)
line)and andcontinue
continueon onthe
thenext
nextline.
line.
•• >>c
>>c==1+2+3+...
1+2+3+...
5+6+7;
5+6+7;
•• There
Thereare areseveral
several predefined
predefinedvariables
variableswhich
whichcancan
be
beused usedat atany
anytime,
time, in
inthe
thesame
samemanner
manneras asuser-
user-
defined
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 ofpredefined
predefinedfunctions
functions
that
thatcan
canbebeused
usedwhen
whendefining
definingaavariable.
variable. Some
Some
common
commonfunctions
functionsthat
thatare
areused
usedin
inthis
thisworkshop
workshop
are:
are:
abs
abs magnitude
magnitudeof ofaanumber
number (absolute
(absolutevalue
valueforfor
real
real numbers)
numbers)
angle
angle angleangleofofaacomplex
complexnumber,
number, in
inradians
radians
cos
cos cosine
cosinefunction,
function, assumes
assumesargument
argumentis isin
in
radians
radians
sin
sin sin
sinfunction,
function, assumes
assumesargument
argumentis isin
in
radians
radians
exp
exp exponential
exponential function
function
MATLAB
MATLAB Basics
Basics
Variables:
Variables:
•• For
Forexample,
example,with
withyydefined
definedasasabove,
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==33asasdefined
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
Note that expcan
that exp canbebeused
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
canbebeverified
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
vector algebra;
algebra;
even
evenscalars
scalarsare
aretreated
treatedas
as11byby11matrices.
matrices.
•• Therefore,
Therefore, vector
vectorand
andmatrix
matrixoperations
operationsare
areas
as
simple
simpleas
ascommon
commoncalculator
calculatoroperations.
operations.
•• The
Thenumber
numberof ofentries
entries(elements
(elementsor orcomponents)
components)
is
isknown
knownasasthe
the"length"
"length"ofofthe
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
Vectorscancanbe bedefined
definedin intwo
twoways.
ways.
The
Thefirst
firstmethod
methodis isused
usedforforarbitrary
arbitraryelements:
elements:
•• >>v
>>v==[1[13355sqrt(49)];
sqrt(49)];
•• creates
createsaa1x41x4vector
vectorwith
withelements
elements1, 1,3,
3,55and
and7.
7.
•• Note
Notethat
thatcommas
commascould couldhave
havebeen
beenused
usedininplace
placeof
ofspaces
spaces
to separate the elements ([1,3,5,sqrt(49)]).
to separate the elements ([1,3,5,sqrt(49)]).
•• Additional
Additionalelements
elementscan canbebeadded
addedto tothe
thevector:
vector:
•• >>v(5)
>>v(5)==8; 8;
•• yields
yieldsthe
thevector
vectorvv==[1 [13355778].
8].
•• Previously
Previouslydefined
definedvectors
vectorscan canbebeused
usedto todefine
defineaanew
new
vector.
vector.
•• For
Forexample,
example,with withvvdefined
definedabove
above
•• >>a
>>a==[9[910];
10];
•• >>b
>>b==[v[va];
a];
•• creates
createsthethevector
vectorbb==[1 [1335577889910].
10].
MATLAB
MATLAB Basics
Basics
Vectors
Vectors and
and Matrices:
Matrices:
•• The
Thesecond
secondmethod method isisused
usedfor
forcreating
creatingvectors
vectors
with
withequally
equallyspacedspacedelements:
elements:
•• >>t
>>t== 0:0.1:10;
0:0.1:10;
•• creates
createsaa1x101 1x101vector
vectorwith
withthe
theelements
elements
0,
0, .1,
.1, .2,
.2, .3,...,10.
.3,...,10.
•• Note
Notethat thatthethemiddle
middlenumber
numberdefines
definesthe
the
increment.
increment.
•• IfIfonly
onlytwo twonumbers
numbersare aregiven,
given, then
thenthe
theincrement
increment
is
isset
setto toaadefault
defaultofof1:
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 areare defined
defined byby entering
entering the
the
elements
elements row row byby 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 bebe defined:
defined:
null
null matrix:
matrix: M
M == [[ ];];
nxm
nxm matrix
matrix ofof zeros:
zeros: M
M == zeros(n,m);
zeros(n,m);
nxm
nxm matrix
matrix ofof ones:
ones: MM == 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
number55ininthe
thefirst
firstrow,
row,second
secondcolumn.
column.
•• Operations
Operationsand andfunctions
functionsthat
thatwere
weredefined
definedfor
forscalars
scalarsininthe
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
Functionsareareapplied
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
Operationsthatthatneed
needtotobe
beperformed
performedelement-by-element
element-by-element
can
canbebeaccomplished
accomplishedby bypreceding
precedingthetheoperation
operationby byaa".".
".".
For
Forexample,
example,to toobtain
obtainaavector
vectorxxthat
thatcontains
containsthetheelements
elements
of
ofx(t)
x(t)==tcos(t)
tcos(t)atatspecific
specificpoints
pointsinintime,
time,you
youcannot
cannotsimply
simply
multiply
multiplythethevector
vectorttwith
withthe
thevector
vectorcos(t).
cos(t).
Instead
Insteadyouyoumultiply
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
lengthofofaavector
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