Sie sind auf Seite 1von 42

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

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 # 3
Friday August 30
MATLAB Plots
MATLAB Fundation
Textbook Examples

Short Quiz

MATLAB
MATLAB Basics
Basics
Vectors
Vectors and
and Matrices:(
Matrices:(Cont.
Cont.))
EXAMPLE:
EXAMPLE:

>>
>>a=2:3,
a=2:3,b=[a
b=[a2*a;a/2
2*a;a/2a]
a]
aa==
22 33
bb==
2.0000
2.0000 3.0000
3.0000 4.0000
4.0000
1.0000
1.0000 1.5000
1.5000 2.0000
2.0000

6.0000
6.0000
3.0000
3.0000

>>
>>c=[b
c=[b;;b]
b]
cc==

2.0000
2.0000
1.0000
1.0000
2.0000
2.0000
1.0000
1.0000

3.0000
3.0000
1.5000
1.5000
3.0000
3.0000
1.5000
1.5000

4.0000
4.0000
2.0000
2.0000
4.0000
4.0000
2.0000
2.0000

6.0000
6.0000
3.0000
3.0000
6.0000
6.0000
3.0000
3.0000

MATLAB
MATLAB Basics
Basics
Vectors
Vectors and
and Matrices:
Matrices:
>>
>>D=c(2:3,
D=c(2:3,2:3)
2:3)
DD==

1.5000
1.5000 2.0000
2.0000
3.0000
4.0000
3.0000 4.0000

>>
who
>>
who
Your variables are:

Your variables are:

>>
whos
>>
whos
Name Size Bytes
Name
DD
aa
bb
cc

Size Bytes
2x2
2x2 32
32
1x2
16
1x2
16
2x4
64
2x4
64
4x4
4x4 128
128

DDaabbcc
Class
Class
double
doublearray
array
double
array
double array
double
doublearray
array
double
doublearray
array

Grand
Grandtotal
totalisis30
30elements
elementsusing
using240
240bytes
bytes

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

>>
>>a=magic(4)
a=magic(4)
a=
a=
16.0000
16.0000 2.0000
2.0000 3.0000
3.0000
5.0000
11.5000
10.0000
5.0000 11.5000 10.0000
9.0000
9.0000 7.0000
7.0000 6.0000
6.0000
4.0000
14.5000
15.0000
4.0000 14.5000 15.0000

13.0000
13.0000
8.0000
8.0000
12.0000
12.0000
1.0000
1.0000

>>
>>sum(a)
sum(a)==sum(a')
sum(a')==[34
[3434
3434
3434]
34]

>>
>>trace(a)
trace(a)==34
34

A(i,
A(i,j)j)indexes
indexesrow
rowi,i,column
columnj j

Indexing
Indexingstarts
startswith
with1,1,not
notzero.
zero.

>>a(a,
>>a(a,3)
3)==33
>>a(3,
>>a(3,1)
1)==39
39
>>a(:,
3)
=
3
>>a(:, 3) = 3 10
10 66 15
15

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

>>a(2:3,3:4)
>>a(2:3,3:4)==

10
10 88
22 12
12
>>a([1
>>a([14],[1
4],[14])
4])==
16
16 13
13
44 11
>>a(8)
>>a(8)==14
14

>>[1:3]
>>[1:3]++[4:6]
[4:6]==55 77 99

A=zeros(2,2);
A=zeros(2,2);B=(ones(3,2);
B=(ones(3,2);

CC==[ [[A-1;B+1],
[A-1;B+1],[B+3;A-4]
[B+3;A-4]],],
CC==
-1
-1 -1
-1 44 44
-1
-1 -1
-1 44 44
22 22 44 44
22 22 -4
-4 -4
-4
22 22 -4
-4
-4 -4

MATLAB
MATLAB Basics
Basics
Plotting
Plotting Elementary
Elementary Functions:
Functions:
MATLAB
MATLAB supports
supports many
many types
types of
of graph
graph and
and
surface
surface plots:
plots:
22 dimensions
dimensions line
line plots
plots (x
(x vs.
vs. y),
y), filled
filled
plots,
plots, bar
bar charts,
charts, pie
pie charts,
charts, parametric
parametric
plots,
plots, polar
polar plots,
plots, contour
contour plots,
plots, density
density
plots,
plots, log
log axis
axis plots,
plots, surface
surface plots,
plots,
parametric
parametric plots
plots in
in 33 dimensions
dimensions and
and
spherical
spherical plots.
plots.
To
Topreview
preview some
some of
of these
these capabilities
capabilities and
and
others
others as
as well,
well, enter
enter the
the command
command demos.
demos.

MATLAB
MATLAB Basics
Basics
Plotting Elementary Functions:
2-D plots: The plot command creates linear x-y plots; if x and y are vectors of the same length, the
command plot(x,y) opens a graphics window and draws an x-y plot of the elements of x versus the
elements of y.

MATLAB
MATLAB Basics
Basics
Plotting
Plotting Elementary
Elementary Functions:
Functions:
>>%
>>%Example
Example E1_2a
E1_2a of
of your
your textbook
textbook on
on page
page 23.
23. (file
(file name
name is
is E1_2.m)
E1_2.m)
>>t=-1:0.01:1;
>>t=-1:0.01:1;
>>f=4.5*cos(2*pi*t
>>f=4.5*cos(2*pi*t -- pi/6);
pi/6);
>>%
>>%The
The following
following statements
statements plot
plot the
the sequence
sequence and
and label
label the
the plot
plot
>>plot(t,f),title('Fig.E1.2a');
>>plot(t,f),title('Fig.E1.2a');
>>axis([-1,1,-6,6]);
>>axis([-1,1,-6,6]);
>>xlabel('t');
>>xlabel('t');
>>ylabel('f(t)');
>>ylabel('f(t)');
>>text(-0.6,5,'f(t)
>>text(-0.6,5,'f(t) == AA cos(wt
cos(wt ++ phi)');
phi)');
>>grid;
>>grid;
Plot on next page

MATLAB
MATLAB Basics
Basics

Plotting

Elementary

Functions:
>>%Example E1_2a

MATLAB
MATLAB Basics
Basics
Plotting
Plotting Elementary
Elementary Functions:
Functions:
PLOT(X,Y)
plots
PLOT(X,Y)
plotsvector
vectorYYversus
versusvector
vectorX.
X.
TITLE('text')
adds
TITLE('text')
addstext
textat
atthe
thetop
topof
ofthe
thecurrent
currentplot.
plot.
XLABEL('text')
XLABEL('text')adds
addstext
textbeside
besidethe
theX-axis
X-axison
onthe
thecurrent
currentaxis.
axis.
YLABEL('text')
YLABEL('text')adds
addstext
textbeside
besidethe
theY-axis
Y-axison
onthe
thecurrent
currentaxis.
axis.
GRID,
by
GRID,
byitself,
itself,toggles
togglesthe
themajor
majorgrid
gridlines
linesof
ofthe
the
current
axes.
current axes.
GTEXT('string')
GTEXT('string')displays
displaysthe
thegraph
graphwindow,
window,puts
putsup
upaacross-hair,
cross-hair, and
and
waits
for
a
mouse
button
or
keyboard
key
to
be
pressed.
waits for a mouse button or keyboard key to be pressed.
SUBPLOT(m,n,p),
SUBPLOT(m,n,p),or
orSUBPLOT(mnp),
SUBPLOT(mnp),breaks
breaksthe
theFigure
Figurewindow
windowinto
intoan
an
m-by-n
matrix
of
small
axes.
m-by-n matrix of small axes.
stemDiscrete
stemDiscretesequence
sequenceor
or"stem"
"stem"plot.
plot.STEM(Y)
STEM(Y)plots
plotsthe
thedata
datasequence
sequence
YYas
stems
from
the
x
axis
terminated
with
circles
for
the
data
as stems from the x axis terminated with circles for the data
value.
value.
SEMILOGX(...)
SEMILOGX(...)isisthe
thesame
sameas
asPLOT(...),
PLOT(...),except
exceptaalogarithmic
logarithmic(base
(base10)
10)
scale
is
used
for
the
X-axis.
scale is used for the X-axis.
SEMILOGY(...)
SEMILOGY(...)isisthe
thesame
sameas
asPLOT(...),
PLOT(...),except
exceptaalogarithmic
logarithmic(base
(base10)
10)
scale
is
used
for
the
Y-axis..
scale is used for the Y-axis..

MATLAB
MATLAB Basics
Basics
Plotting
Plotting Elementary
Elementary Functions:
Functions:
By
Bydefault,
default,the
theaxes
axesare
areauto-scaled.
auto-scaled.
This
Thiscan
canbe
beoverridden
overridden by
bythe
thecommand
command axis.
axis.IfIf cc ==
[xmin,xmax,ymin,ymax]
[xmin,xmax,ymin,ymax] is
isaa
4-element
4-element vector,
vector,then
then axis(c)
axis(c)sets
setsthe
theaxis
axisscaling
scaling
to
tothe
theprescribed
prescribedlimits.
limits.
By
Byitself,
itself,axis
axisfreezes
freezesthe
thecurrent
current scaling
scalingfor
for
subsequent
subsequent graphs;
graphs; entering
enteringaxis
axisagain
againreturns
returnsto
to
auto-scaling.
auto-scaling.
The
Thecommand
command axis('square')
axis('square') ensures
ensuresthat
that the
thesame
same
scale
scaleis
isused
usedon
onboth
bothaxes.
axes.
For
Formore
moreinformation's
information'son
onaxis
axissee
seehelp
helpaxis.
axis. ..

MATLAB
MATLAB Basics
Basics
Plotting
Plotting Elementary
Elementary Functions:
Functions:

>>%Example
>>%Example1.2
1.2of
ofyour
yourtextbook
textbookon
onpage
page24.
24.(file
(filename
nameisisE1_2d.m)
E1_2d.m)

>>t=-0.5:0.01:3;
>>t=-0.5:0.01:3;

>>t0=0
>>t0=0

>>u=stepfun(t,t0)
>>u=stepfun(t,t0)

>>gprime=3.17*exp(-1.3*t).*cos(10.8*t
>>gprime=3.17*exp(-1.3*t).*cos(10.8*t++1.15).*u;
1.15).*u;
%
NOTE
the
use
of
the
.*
operator.
The
terms
3.17*exp(-1.3*t),
% NOTE the use of the .* operator. The terms 3.17*exp(-1.3*t),
%
%cos(10.8*t
cos(10.8*t++1.15),
1.15),and
anduuare
areall
allvectors.
vectors.We
Wewant
wantthe
the
%
%components
componentsof
ofthese
thesevectors
vectorsto
tobe
bemultiplied
multipliedby
bythe
thecorresponding
corresponding
%
%components
componentsof
ofthe
theother
othervectors,
vectors,hence
hencethe
theneed
needto
touse
use.*.* rather
ratherthan
than*.*.
%
%The
Thefollowing
followingstatements
statementsplot
plotthe
thesequence
sequenceand
andlabel
labelthe
theplot
plot

>>plot(t,gprime);
>>plot(t,gprime);

>>axis([-.5,3,-3,2]);
>>axis([-.5,3,-3,2]);

>>title('Fig.E1.2d');
>>title('Fig.E1.2d');

>>xlabel('t
>>xlabel('tin
inseconds');
seconds');

>>ylabel('gprime(t)');
>>ylabel('gprime(t)');

>>text(-0.6,5,'f(t)
>>text(-0.6,5,'f(t)==AAcos(wt
cos(wt++phi)');
phi)');

>>grid;
>>grid;

MATLAB
MATLAB Basics
Basics

Plotting

Elementary

Functions:
>>%Example E1.2

MATLAB
MATLAB Basics
Basics
Plotting
Plotting Elementary
Elementary Functions:
Functions:
Two
Twoways
waysto
tomake
makemultiple
multipleplots
plotson
onaasingle
singlegraph
graphare
areillustrated
illustratedby
by

>>t
>>t==0:.01:2*pi;
0:.01:2*pi;
>>y1
>>y1==sin(t);
sin(t);y2=sin(2*t);
y2=sin(2*t);y3=sin(4*t)
y3=sin(4*t)
>>plot(t,y1,y2,y3)
>>plot(t,y1,y2,y3)
and
andby
byforming
formingaamatrix
matrixYYcontaining
containingthe
thefunctional
functionalvalues
valuesas
ascolumns
columns
>>t
=
0:.01:2*pi;
>>t = 0:.01:2*pi;
>>y
>>y==[sin(t)',
[sin(t)',sin(2*t)',
sin(2*t)',sin(4*t)']
sin(4*t)']
>>plot(t,y)
>>plot(t,y)
Another
Anotherway
wayisiswith
withthe
thehold
holdcommand.
command.The
Thecommand
commandhold
holdfreezes
freezesthe
the
current
graphics
screen
so
that
subsequent
plots
are
superimposed
current graphics screen so that subsequent plots are superimposedon
onit.
it.
Entering
hold
again
releases
the
"hold".
The
commands
hold
on
and
hold
Entering hold again releases the "hold". The commands hold on and holdoff
off
are
also
available.
are also available.
One
Onecan
canoverride
overridethe
thedefault
defaultlinotypes
linotypesand
andpoint
pointtypes.
types.For
Forexample,
example,
>>t
=
0:.01:2*pi;
>>t = 0:.01:2*pi;
>>y1
>>y1==sin(t);
sin(t);y2=sin(2*t);
y2=sin(2*t);y3=sin(4*t)
y3=sin(4*t)
>>plot(t,y1,'--',y2,':',y3,'+')
>>plot(t,y1,'--',y2,':',y3,'+')

MATLAB
MATLAB Basics
Basics
Plotting
Plotting Elementary
Elementary Functions:
Functions:

Colors
Line
Colors
LineStyles
Styles

yy yellow
. . point
yellow
point

MM magenta
oo circle
magenta
circle

CC cyan
xx x-mark
cyan
x-mark

RR red
++ plus
red
plus

GG green
-- solid
green
solid

BB blue
** star
blue
star

W
:: dotted
W white
white
dotted

KK black
-.
Dashdot
black
-. Dashdot

---- dashed
dashed
More
Moremark
marktypes
typesare;
are;square(s),
square(s),diamond(d),
diamond(d),up-triangle(v),
up-triangle(v),downdowntriangle(^),
left-triangle(<),
right-triangle(>),
pentagram(p),
triangle(^), left-triangle(<), right-triangle(>), pentagram(p),
hexagram(h)
hexagram(h)
See
Seealso
alsohelp
helpplot
plotfor
formore
moreline
lineand
andmark
markcolor.
color.

MATLAB
MATLAB Basics
Basics
Plotting
Plotting Elementary
Elementary Functions:
Functions:

The
Thecommand
commandsubplot
subplotcan
canbe
beused
usedto
topartition
partitionthe
thescreen
screenso
sothat
thatup
upto
to
four
plots
can
be
viewed
simultaneously.
See
help
subplot.
four plots can be viewed simultaneously. See help subplot.

Example
Examplefor
foruse
useof
ofsubplot:
subplot:

>>%
>>%Line
Lineplot
plotof
ofaachirp
chirp

>>
>>x=0:0.05:5;
x=0:0.05:5;

>>
>>y=sin(x.^2);
y=sin(x.^2);

>>
>>subplot(2,2,1),
subplot(2,2,1),plot(x,y);
plot(x,y);

>>
>>%
%Bar
Barplot
plotof
ofaabell
bellshaped
shapedcurve
curve

>>
>>xx==-2.9:0.2:2.9;
-2.9:0.2:2.9;

>>
>>subplot(2,2,2),
subplot(2,2,2),bar(x,exp(-x.*x));
bar(x,exp(-x.*x));

>>
%
Stem
plot
>> % Stem plot

>>
>>xx==0:0.1:4;
0:0.1:4;

>>
>>subplot(2,2,3),
subplot(2,2,3),stem(x,y)
stem(x,y)

>>
>>%
%Polar
Polarplot
plot

>>
>>t=0:.01:2*pi;
t=0:.01:2*pi;

>>
>>subplot(2,2,4),
subplot(2,2,4),polar(t,abs(sin(2*t).*cos(2*t)));
polar(t,abs(sin(2*t).*cos(2*t)));

MATLAB
MATLAB Basics
Basics

Plotting

Elementary

Functions:
>>%Example Subplot

MATLAB
MATLAB Basics
Basics
Loading
Loading and
and Saving:
Saving:

When
Whenusing
usingMATLAB,
MATLAB,you
youmay
maywish
wishto
toleave
leavethe
theprogram
programbut
butsave
save
the
vectors
and
matrices
you
have
defined.
the vectors and matrices you have defined.
SAVE,
SAVE,Save
Saveworkspace
workspacevariables
variablesto
todisk.
disk.
SAVE
FILENAME
saves
all
workspace
SAVE FILENAME saves all workspacevariables
variablesto
tothe
thebinary
binary"MAT"MATfile"
named
FILENAME.mat.
file" named FILENAME.mat.
The
Thedata
datamay
maybe
beretrieved
retrievedwith
withLOAD.
LOAD.
IfIfFILENAME
FILENAMEhas
hasno
noextension,
extension,.mat
.matisisassumed.
assumed.
SAVE,
by
itself,
creates
the
binary
"MAT-file"
SAVE, by itself, creates the binary "MAT-file"named
named'matlab.mat'.
'matlab.mat'.
ItItis
isan
anerror
errorifif'matlab.mat'
'matlab.mat'is
isnot
notwritable.
writable.
To
Tosave
savethe
thefile
fileto
tothe
theworking
workingdirectory,
directory,type
type
>>save
>>savefilename
filename
SAVE
SAVEFILENAME
FILENAMEXXsaves
savesonly
onlyX.
X.
SAVE
SAVEFILENAME
FILENAMEXXYYZZsaves
savesX,
X,Y,
Y,and
andZ.
Z.
where
"filename"
is
a
name
of
your
choice.
where "filename" is a name of your choice.To
Toretrieve
retrievethe
thedata
datalater,
later,
type.
type.

MATLAB
MATLAB Basics
Basics
Loading
Loading and
and Saving:
Saving:

LOAD
LOADLoad
Loadworkspace
workspacevariables
variablesfrom
fromdisk.
disk.
LOAD
LOADFILENAME
FILENAMEretrieves
retrievesall
allvariables
variablesfrom
fromaafile
filegiven
givenaafull
full
pathname
pathnameor
oraaMATLABPATH
MATLABPATHrelative
relativepartial
partialpathname
pathname(see
(see
PARTIALPATH).
PARTIALPATH).
IfIfFILENAME
FILENAMEhas
hasno
noextension
extensionLOAD
LOADlooks
looksfor
forFILENAME
FILENAME
and
andFILENAME.mat
FILENAME.matand
andtreats
treatsititas
asaabinary
binary"MAT-file".
"MAT-file".
IfIfFILENAME
FILENAMEhas
hasan
anextension
extensionother
otherthan
than.mat,
.mat,ititis
istreated
treatedas
as
ASCII.
ASCII.
LOAD,
LOAD,by
byitself,
itself,uses
usesthe
thebinary
binary"MAT-file"
"MAT-file"named
named
'matlab.mat'.
'matlab.mat'.ItItis
isan
anerror
errorifif'matlab.mat'
'matlab.mat'is
isnot
notfound.
found.
LOAD
LOADFILENAME
FILENAMEXXloads
loadsonly
onlyX.
X.
LOAD
LOADFILENAME
FILENAMEXXYYZZ...
...loads
loadsjust
justthe
thespecified
specifiedvariables.
variables.
>>load
>>loadx,
x,y,y,zz
See
Seehelp
helpsave
saveand
andhelp
helpload
loadfor
formore
moreinformation..
information..

MATLAB
MATLAB Basics
Basics
M-Files:
M-Files:
M-files
M-files are
are macros
macros of
of MATLAB
MATLAB commands
commands
that
that are
are stored
stored as
as ordinary
ordinary text
text files
files with
with
the
the extension
extension "m",
"m", that
that is
is filename.m.
filename.m.
An
An M-file
M-file can
can be
be either
either aa function
function with
with input
input
and
and output
output variables
variables or
or aa list
list of
of commands.
commands.
All
All of
of the
the MATLAB
MATLAB file
file in
in EE
EE 327
327 textbook
textbook
are
are contained
contained in
in M-files
M-files that
that are
are available
available at
at
the
the site
site http://www.csee.wvu.edu/~jalali.
http://www.csee.wvu.edu/~jalali.

MATLAB
MATLAB Basics
Basics
M-Files:
M-Files:

The
Thefollowing
followingdescribes
describesthe
theuse
useof
ofM-files
M-fileson
onaaPC
PCversion
versionof
of
MATLAB.
MATLAB.
MATLAB
MATLABrequires
requiresthat
thatthe
theM-file
M-filemust
mustbe
bestored
storedeither
eitherin
inthe
the
working
directory
or
in
a
directory
that
is
specified
in
the
working directory or in a directory that is specified in the
MATLAB
MATLABpath
pathlist.
list.
For
Forexample,
example,consider
considerusing
usingMATLAB
MATLABon
onaaPC
PCwith
withaauseruserdefined
M-file
stored
in
a
directory
called
defined M-file stored in a directory called
"\MATLAB\MFILES";.
"\MATLAB\MFILES";.
Then
Thento
toaccess
accessthat
thatM-file,
M-file,either
eitherchange
changethe
theworking
working
directory
directoryby
bytyping
typingcd\matlab\mfiles
cd\matlab\mfilesfrom
fromwithin
withinthe
theMATLAB
MATLAB
command
commandwindow
windowor
orby
byadding
addingthe
thedirectory
directoryto
tothe
thepath.
path.
Permanent
Permanentaddition
additionto
tothe
thepath
pathis
isaccomplished
accomplishedby
byediting
editing
the
the\MATLAB\matlabrc.m
\MATLAB\matlabrc.mfile.
file.
Temporary
Temporarymodification
modificationto
tothe
thepath
pathis
isaccomplished
accomplishedby
by
typing
path(path,'\matlab\mfiles')
from
within
MATLAB.
typing path(path,'\matlab\mfiles') from within MATLAB.

MATLAB
MATLAB Basics
Basics
M-Files:
M-Files:
The
The M-files
M-files associated
associated with
with this
this textbook
textbook
should
should be
be downloaded
downloaded from
from the
the EE
EE 327
327 site
site
and
and copied
copied to
to aa subdirectory
subdirectory named
named
"\MATLAB\users";
"\MATLAB\users"; and
and then
then this
this directory
directory
should
should be
be added
added to
to the
the path.
path.
The
The M-files
M-files that
that come
come with
with MATLAB
MATLAB are
are
already
already in
in appropriate
appropriate directories
directories and
and can
can
be
be used
used from
from any
any working
working directory.
directory.

MATLAB
MATLAB Basics
Basics
M-Files
M-Files Functions:
Functions:
As
Asan
anexample
exampleof
of M-file
M-filethat
thatdefines
definesaafunction,
function,
create
createaafile
filein
inyour
yourworking
workingdirectory
directorynamed
named
yplusx.m
yplusx.m that
thatcontains
containsthe
thefollowing
followingcommands:
commands:
function
functionzz==yplusx(y,x)
yplusx(y,x)
zz==yy++ x;
x;
The
Thefollowing
followingcommands
commandstyped
typedfrom
from within
within
MATLAB
MATLABdemonstrate
demonstratehow
how this
thisM-file
M-file is
isused:
used:
xx==2;
2;
yy==3;
3;
zz==yplusx(y,x)
yplusx(y,x)

MATLAB
MATLABM-files
M-filesare
aremost
mostefficient
efficientwhen
whenwritten
writtenininaaway
waythat
thatutilizes
utilizesmatrix
matrixor
or
vector
operations.
vector operations.

MATLAB
MATLAB Basics
Basics
Loops
Loops and
and If
If statements
statements (Control
(Control Flow):
Flow):
Loops
Loopsand
andififstatements
statementsare
areavailable,
available,but
butshould
shouldbe
beused
used
sparingly
sparinglysince
sincethey
theyare
arecomputationally
computationallyinefficient.
inefficient.
An
Anexample
exampleof
ofthe
theuse
useof
ofthe
thecommand
commandfor
foris
is
for
fork=1:10,
k=1:10,
x(k)
x(k)==cos(k);
cos(k);
end
end
This
Thiscreates
createsaa1x10
1x10vector
vectorxxcontaining
containingthe
thecosine
cosineof
ofthe
thepositive
positive
integers
integersfrom
from11to
to10.
10.
This
Thisoperation
operationis
isperformed
performedmore
moreefficiently
efficientlywith
withthe
the
commands
commands
kk==1:10;
1:10;
xx==cos(k);
cos(k);

which
whichutilizes
utilizesaafunction
functionof
ofaavector
vectorinstead
insteadof
ofaafor
forloop.
loop.

MATLAB
MATLAB Basics
Basics
If
If statements:
statements:
An
Anifif statement
statementcan
can be
beused
usedto
todefine
define conditional
conditional
statements.
statements.
An
Anexample
exampleis
is
if(a
if(a<=
<= 2),
2),
bb == 1;
1;
elseif(a
elseif(a >=4)
>=4)
bb == 2;
2;
else
else
bb == 3;
3;
end
end
The
Theallowable
allowable comparisons
comparisonsbetween
between expressions
expressions
are
are >=,
>=, <=,
<=, <,
<, >,
>, ==,
==,and
and ~=.
~=.

MATLAB
MATLAB Basics
Basics
While
While Loops
Loops statements
statements (Control
(Control Flow):
Flow):

While
While for
forloop
loopevaluates
evaluatesaagroup
groupof
ofcommands
commandsaafixed
fixednumber
numberof
oftimes,
times,
AAwhile
loop
evaluates
a
group
of
statements
an
infinite
number
of
while loop evaluates a group of statements an infinite number oftimes.
times.
The
general
form
of
a
while
loop
is
The general form of a while loop is
while
whileexpression
expression
commands
commands
end
end
The
Thecommand
commandbetween
betweenthe
thewhile
whileand
andend
endstatements
statementsare
areexecuted
executedas
as
long
longas
asALL
ALLexpression
expressionare
aretrue.
true.

Example
the special MATLAB value eps. ESP is a variable it is different from esp.)
Example((computing
computing the special MATLAB value eps. ESP is a variable it is different from esp.)
>>num=0;
>>num=0;EPS=1;
EPS=1;
>>while
(1+EPS)>1
>>while (1+EPS)>1
EPS=EPS/2;
EPS=EPS/2;
num=num+1;
num=num+1;
end
end
>>num
>>num
num
num==53.
53.
>>EPS=2*EPS
>>EPS=2*EPS
EPS=
EPS=2.2204e-16
2.2204e-16

MATLAB
MATLABUSED
USED16
16digit
digitso
soeps
epsisisnear
near10^-16.
10^-16.

MATLAB
MATLAB Basics
Basics
User
User Defined
Defined Variable:
Variable:
Several
Severalof
ofthe
theM-files
M-fileswritten
writtenfor
forthis
thistextbook
textbookemploy
employaauseruserdefined
definedvariable
variablewhich
whichis
isdefined
definedwith
withthe
thecommand
commandinput.
input.
For
Forexample,
example,suppose
supposethat
thatyou
youwant
wantto
torun
runan
anM-file
M-filewith
with
different
differentvalues
valuesof
ofaavariable
variableT.
T.
The
Thefollowing
followingcommand
commandline
linewithin
withinthe
theM-file
M-filedefines
definesthe
the
value:
value:
TT==input('Input
input('Inputthe
thevalue
valueof
ofT:
T:')')

Whatever
Whatevercomment
commentis
isbetween
betweenthe
thequotation
quotationmarks
marksis
is
displayed
displayedto
tothe
thescreen
screenwhen
whenthe
theM-file
M-fileis
isrunning,
running,and
andthe
the
user
usermust
mustenter
enteran
anappropriate
appropriatevalue.
value.

Use
Usehelp
helpcommand
commandfor:
for:diary,
diary,save,
save,load,
load,who
whoand
andwhos
whosfind
find
out
outmore
moreabout
aboutthem.
them.

MATLAB
MATLAB Examples
Examples
Some
Some on
on line
line
Demos
Demos and
and
Examples.
Examples.

Simulink
Simulink
Graphical
Graphical block
block diagram
diagram capability
capability
Can
Can drag
drag and
and drop
drop components
components (called
(called
blocks)
blocks)

Extensive
Extensive library
library of
of blocks
blocks available
available
DSP
DSP Blockset
Blockset is
is one
one

Real-time
Real-time Workshop
Workshop

Simulink
Simulink
An
An environment
environment for
for building
building and
and
simulating
simulating models.
models.
Continuous,
Continuous, discrete
discrete or
or hybrid
hybrid systems
systems
Linear
Linear and
and nonlinear
nonlinear components
components
Can
Can simulate
simulate asynchronous
asynchronous events
events

Closely
Closely integrated
integrated with
with MATLAB
MATLAB and
and
toolboxes
toolboxes

Simulink
Simulink Model
Model
AAtypical
typicalSimulink
Simulinkmodel
modelincludes
includesSources,
Sources,Systems
Systemsand
andSinks.
Sinks.

1.
2.
3.
4.

Sinewaves
Function
Generators
From MATLAB
workspace
From Disk Files

Sinks

Systems

Sources

1.

Interconnection
of Linear and
Nonlinear blocks

1.
2.
3.
4.

Displays scopes
FFT scopes
To MATLAB
workspace
To disk files

Simple
Simple Simulink
Simulink Model
Model

Scope
2
Sine Wave

Gain
Gain1

Sum
0.9

Scope1
Unit Delay

1
z

Simulink
Simulink Block
Block Libraries
Libraries

Simulink contains block libraries, which contain components that


can be used to build models.

A block library can itself have other libraries as blocks. Example:


When you first start Simulink:

In1

Sources
Blocksets &
Toolboxes

Sinks

Discrete

Linear

Nonlinear

Simulink Block Library 2.2


Copyright (c) 1990-1998 by The MathWorks, Inc.

Out1

Scope

XY Graph

Connections

Demos

Sinks is itself a
block library of
components

Display
untitled.mat

simout

To File

To Workspace
STOP

Stop Simulation

Building a Simulink Model


1

Sine Wave

Sum

Model Window

Sum

s
Integrator

Transfer Fcn

s+1

(s-1)

x' = Ax+Bu
y = Cx+Du

s(s+1)

State-Space

Zero-Pole

du/dt

Use left
mouse
button to
drag blocks
to the
model
window

Gain

Constant

Signal
Generator

Step

Ramp

Sine Wave

Repeating
Sequence

Discrete Pulse
Generator

Pulse
Generator

Chirp Signal
12:34

Clock

Digital Clock

untitled.mat

[T,U]

From File

From
Workspace

Random
Number

Uniform Random
Number

Band-Limited
White Noise

Derivative

Dot Product

Matrix
Gain

Slider
Gain

Linear Blocks
Library

Sources Library

Connecting
Connecting Blocks
Blocks
1

1
Sine Wave

Sine Wave

Gain

Gain

Sum

Sum

Sine Wave

Gain

Sum

Use the left mouse


button to click on a port
and drag a connection

1
Sine Wave

Gain

Sum

Scope

1
Sine Wave

Use the right mouse


button to click on a line
to drag a branch line

Gain

Sum

Scope

More
More Simulink
Simulink Basics
Basics
Double-click on a block to open its Dialog Box.
Parameters for the block can be set in this box.
Example: setting the amplitude, frequency, phase and
sampling frequency of the sinewave source.

Click on the HELP button on the Dialog Box for a


block to launch the Web Browser opened at the
HELP file for that component.
After selecting a block, you can rotate, flip or
resize it. These operations are useful in creating a
more readable block diagram.

Setting
Setting Simulation
Simulation Parameters
Parameters
The
TheSimulation
Simulation menu
menu item
item on
onthe
themodels
modelswindow
window
can
canbe
beused
usedto
toset
setsimulation
simulation parameters.
parameters.
You
Youcan
canspecify
specifythe
theappropriate
appropriatesolver
solverthat
thatis
isto
to
be
beused.
used.For
Fordiscrete-time
discrete-timesystems
systemsuse
use

the
theFixed-step
Fixed-stepDiscrete
Discretesolver
solverififthere
thereis
isonly
onlyaasingle
single
sample
sampletime.
time.
The
TheVariable-step
Variable-stepDiscrete
Discretesolver
solverfor
formultirate
multiratesystems.
systems.

You
Youcan
canalso
alsospecify
specifyvariables
variablesthat
thatare
areto
tobe
be
obtained
obtained from
fromor
orreturned
returnedto
tothe
theMATLAB
MATLAB
workspace.
workspace.

Subsystems
Subsystems

You can select portions of your model using the mouse and make them
into a subsystem.

Function
Generator

Zero-Order
Hold

This figure demonstrates


a simple first order IIR filter

Original
Signal

In1
Out1

Filtered
Signal

My 1st order
filter

You can created a masked subsystem, that hides the complexity of the
subsystem from the user.
1
Function
Generator

Zero-Order
Hold

This figure demonstrates


a simple first order IIR filter

Original
Signal

B0
B0

Sum

A1

In1
Out1

My 1st order
filter

In1

Filtered
Signal

A1

1
z
Unit Delay

1
Out1

MATLAB
MATLAB WORKSHOP
WORKSHOP
End of Lecture # 3

MATLAB Advance
Next

time

Das könnte Ihnen auch gefallen