Documente Academic
Documente Profesional
Documente Cultură
SimulinkTUTORIALbyT.Nguyen
|Matlab||ControlSystemsApplications||SymbolicCalculation||SideNotes||Aboutthissite|
SIMULINKEXAMPLES
Example1.SimulationofanEquation.
InthisexamplewewilluseSimulinktomodelanequation.Let'sconsider
(1)
>
M
E
N
U
wherethedisplacementxisafunctionoftimet,frequencyw,phaseanglephi,and
amplitue A. In this example the values for these parameters are set as follows:
frequency=5rad/secphase=pi/2A=2.
1.FromSimulink'slibrarydragthefollowingblockstotheModelWindow
>
Blocks to be dragged to the WherelocatedinSimulinklibrarybrowser
modelwindow
Ramp
Sources
Constant
Sources
Gain
MathOperation
Sum
MathOperation
Product
MathOperation
TrigonometryFunction
MathOperation
Scope
Sinks
Mux
SignalRouting
2.ThenextstepistoconnecttheseblocksasshowninFigureE11.
FigureE11
Doubleclickontheblocksandentertheappropriatevaluesaspromptedbythepop
updialogwindows.Notethatthecosinefunctioncanbeselectedfromthepulldown
http://edu.levitas.net/Tutorials/Matlab/Simulink/examples.html
1/11
4/4/2016
SimulinkTUTORIALbyT.Nguyen
menuinthepopupwindow.Inthearrangementshownabove,theinputsignal(a
rampfunction)istobedisplayedalongwiththeoutput(displacement)viatheuseof
themuxtoolasdemonstratedearlierinthistutorial.Toviewtheplots,doubleclickon
thescope.
3.Makesureallblocksareconnectedcorrectlythenrunthesimulation(CTRL+T).
YoumayneedtoselecttheAutoscalebutton
onthescopedisplaywindowto
obtainabetterdisplayoftheplots.
Youmayfindthesinusoidalplotstobeabit"jaggy".Youmaywanttoimprovethe
resolutionofthedisplayedplotbyredefiningtheMaxStepSidevalue("auto"isseta
defaultvalue)inSimulationParameterswindow(withkeystrokesCTRL+Einthe
modelwindow).Justforfun,youmaywanttoexperiementwithdifferentchoiceof
solver.ODE45isadefaultchoice.Youareencouragedtolearnmoreaboutthesolver
methodsbycheckingoutthehelpfilesinMatlabcommandwindow.Forinstance,
helpODE45forparametersinnonstiffdifferentialequations.
ThisexamplehasdemonstratedtheuseSimulinkwithbuiltinmathematical
functionsandothersupportingtoolboxestosimulateanequation.Thesame
output/resultcanalsobeobtainedwiththefollowingsetofinstructionsenteredin
Matlabcommandwindow:
>>t=(0:.01:10)A=2phi=pi/2omega=5
>>xt=A*cos(omega*t+phi)
>>plot(t,xt)grid
______________________________________
Example2.MassSpringDashpotSystemSimulation
Consider a massspringdashpot system as shown in Figure E21.
Themathematicalmodelforthissystemisdescribedby
(2)
wherem is the equivalent mass of the system, c is the damping
ratio,kisthespringstiffness,andf(t)istheforcingfunctioninthe
xdirection.
InthisexampleIwillillustratehowtouseSimulinktosimulatethe
responseofthissystemtounitstepinput.
FigureE21
STEP1
InSimulink,createanewmodelwindow(CTRL+N)anddragthe
followingblocksfromtheSimulinklibrarywindow:
Blockstobedraggedtothe Where located
modelwindow
browser
Step
Sources
Gain
MathOperation
Sum
MathOperation
Integrator
Continuous
Scope
Sinks
ToWorkspace
Sinks
in
Simulink
library
STEP2
ByrearrangingEqn2toyieldanexpressionfortheaccelerationterm,
Eqn(2)becomes
http://edu.levitas.net/Tutorials/Matlab/Simulink/examples.html
2/11
4/4/2016
SimulinkTUTORIALbyT.Nguyen
(3)
BasedonEqn3,weconnecttheblocksinthediagramasshownin
FigureE22.UseCTRL+FandCTRL+Rtoflipandrotatetheblocksas
necessary(selecttheblockfirstthenexecutethekeysequence).Note
thatyoucanuseCTRL+rightmousebuttontocreatebranchesofthe
connectinglines.Don'tworryabouttheparametervaluesandthesigns
fortheseblocksatthispointaswe'lltakecareofthisinSTEP3.Just
getthemconnectedfirst.
FigureE22
STEP3
Enterthevaluesoftheparametersforeachblock.Inthisexample,we
willsetm=2.0c=0.7k=1.Youareencouragedtotrydifferent
valuesandobservethesystem'sresponsetostepinput.
Toshowthatyoumayobtaindifferentformofoutput,Iincluded
anotherblock(inadditiontothescopeblock)called"simout".Thisblock
canbefoundintheSinksgroupfromtheSimulinkLibrarybrowser.The
outputfromthisblockisusedinMatlabworkspace.Toillustratehow
thisblockworks,Iwillselectanamefortheoutputcalled"simout"as
thevariablenameintheblock'sparametersetting(doubleclickonthe
"simput"blocktobringuptheparameterdialogwindow).Inadditon,I
willneedatimearrayfromthesimulation.Thiscanbespecifedasa
parameterintheSimulationParameterwindow(CTRL+E)underthe
WorkspaceI/OtabasshowninFigureE23.
FigureE23
STEP4
Runthesimulationbyclickingonthe
button(alternatelyyoumay
usekeyboardcommandCTRL+T).Thescreenshotoftheoutputfrom
theScopeblockisshowinFigureE23.
http://edu.levitas.net/Tutorials/Matlab/Simulink/examples.html
3/11
4/4/2016
SimulinkTUTORIALbyT.Nguyen
FigureE23
That'sit!Youhavesuccessfullymodeledandsimulatedasecondorder
underdampeddynamicsystem.Toexamdifferentresponses,feelfree
tochangedifferentvaluesform,c,andkinthegainblocks.
Toseehowyoucanusetheoutputfromthe"simout"block(bythe
way,youmaynametheblockwhateveryouwish),gotoMatlab
Commandwindowandtype
>>who
YoushouldreceiveanechofromMatlablistingthefollowingvariables:
"simout"and"time"(andperhapsothersvariablesinthecurrent
workspacememory).
Now,youmaycreateaplotofthesystemresponseidenticaltothat
shownintheScopeoutput.Thecommandforcreatingthisplotis:
>>plot(time,simout)grid
Notethattheoutoutformatusedintheexampleaboveismatrixtype.
Theoutputsenttoworkspacecanbeusedforfurtheranalysisand
storageinasciiformat.Outputtoworkspaceallowsmoreoptionsinplot
presentationandfurtherdataanalysisasthearraysareinasciiformat.
Example 3. Using the same system presented in Example 2, we will simulate the
responseusingtransferfunctionapproach.
STEP InanewSimulinkmodelwindow,dragthefollowingblocksfromtheSimulink
1
librarywindow:Step(fromSources),TransferFunction(fromContinous),Scope
(fromSinks),andSaveFiletoWorkspace(fromSinks).
STEP ArrangetheblocksasshowninFigureE31below.
2
http://edu.levitas.net/Tutorials/Matlab/Simulink/examples.html
4/11
4/4/2016
SimulinkTUTORIALbyT.Nguyen
FigureE31
NOTE:Block'sbackgroundcolour:Rightclickontheblockandselectthecolour
fromBackgroundColormenu.
STEP Enteringblocks'parametersvalues.
3
We'llusethesamevaluesform,c,andkasinExample2.Doubleclickonthe
transfer function to bring up the parameter diaglog window and enter the
valuesforthecoefficientsinthedenominatorasshowninFigureE32.
NotethattheTransferfunctionblockhasadefautformoffirstorderinthe
denominator(s+1).Youmayspecifydifferentorderforthenumeratorandthe
denominatorbyenteringthecoefficientsassociatedwiththepolynomials.
FigureE32
ClickOKtoclosethedialog.DoubleclickontheSaveOutputToAFileblockto
openthedialogwindowasshowninFigureE33.IntheFilenameboxspecify
thepathandthenameofthefileyouwishtosave.Thesavedfilewillbein.MAT
format(yes,it'sinbinaryformat!Sodon'ttrytoreadit).Youwillbeabletoload
thisfiletoMatlabworkspacelateron.Makesuretorememberwhereyousave
thefileto.Inthisexample,I'llputthefileinmyDdriveunder"temp"directory
andnamethefile"example3out.mat".Youmaychooseotherconvenient
locationonyourcomputer.
In the Variable name box, enter a name of your choice. Here I name the
variable"simout".
Leaveotherparametersindefautsettingsunlessyouwishtoobtainmoreplot
pointsbychangingtheSampleTimesetting.
http://edu.levitas.net/Tutorials/Matlab/Simulink/examples.html
5/11
4/4/2016
SimulinkTUTORIALbyT.Nguyen
FigureE33
STEP Runthesimulationbyclickingonthebutton(alternatelyyoumayusekeyboard
4
commandCTRL+T).ThescreenshotoftheoutputfromtheScopeblockisshow
inFigureE34.
FigureE34
NowbycomparingFigureE23andFigureE34youwillseethatthereponses
areidentical.Nosurpriseheresincethesefigureseffectivelyrepresentthesame
system,onlythelatterinvolvesfewernumberofblocks!
LOADINGMATFILE
Use the load command to "import" the save *.mat file generated from the
simulation.
Note: In this example, I set the path to the directory where the file
"example3out.mat"issaved.IfyoudonotsetthepathinMatlab,youhaveto
http://edu.levitas.net/Tutorials/Matlab/Simulink/examples.html
6/11
4/4/2016
SimulinkTUTORIALbyT.Nguyen
in
the
load
command,
e.g.,
>>load
InMatlabcommandwindow,enterthefollowings:
>>loadexample3out
YoumaywanttoverifytheloadingbyaskingMatlabtolistallofthevariablesin
thecurrentworkspace:
>>who
If the loading is successful, you should see the variable you specified earlier
listedthecurrentworkspace.Inthisexample,Matlabechos:
Yourvariablesare:
simout
"simout" is a 2 x m matrix, where m is number of columns reflecting the
numberofdatapointsgeneratedfromthesimulation.Thefirstrowcontainsthe
timearray.
To generate a plot of the step input response from the simulation, simply use
the plot command on "simout" matrix. For this example, the following
commandproducestheplotshowninFigureE35.
>>plot(simout(1,:),simout(2,:))grid
FigureE35
Insummary,thesimulationsofasecondordercontinuoussystemmodeledby
Equation 2 have been shown using two different approaches. Different file
outputoptionsfromSimulinkwerealsodemonstrated.
____________________________________________________________
Example4.
Inthisexample,we'llconsiderthesamesystemasdescribedinExample3.But
insteadofusingstepinput,we'llexcitethesecondordersystemwithimpulseload.
Inaddition,wewillsimulatetheresponseusingastatespacemodel.
NOTESONIMPULSEFUNCTION
Impulsefunctionisusefulinthesimulatoinofimpactorsuddenloadssuchasthe
strikingofathetipofthepoleagainstaballinapoolgame.Unitimpulsefunction
http://edu.levitas.net/Tutorials/Matlab/Simulink/examples.html
7/11
4/4/2016
SimulinkTUTORIALbyT.Nguyen
atadesiredinstantaisdefinedby
(4)
Equation4isalsoknownasDiracdeltafunction.
To simulate unit impulse in Simulink, we'll use a twoblock step function set as
shownbelow.
SOMENOTESONSTATESPACEAPPROACH
The concept of the state of the system is utilized extensively in the timedomain
analysis and design of control systems. The state variables (along with the input
functions) used in equations describing the dynamics of a system provide the
futurestateofthesystem.Mathematically,thestateofthesystemisdescribedby
asetoffirstorderdifferentialequationintermsofstatevariables.
For our example, we will express the natural state variables,e.g., position and
velocity,ofthesystemintermsofthefollowingvariables:
(5)
where x1 represents the position and x2 represents the velocity of the system.
WiththenewstatevariablesdefinedinEq.5,Eq.3becomes
(6)
Inamatrixform:
(7)
Equation7maybeexpressedinamorecompactform:
(8)
whereAisknownasthesystemmatrixandBastheinputmatrix.
Theoutputequationisexpressedby
http://edu.levitas.net/Tutorials/Matlab/Simulink/examples.html
8/11
4/4/2016
SimulinkTUTORIALbyT.Nguyen
(9)
where
(10)
and
(11)
CiscalledtheoutputmatrixandDiscalledthedirecttransmittancematrix.
MATLABANDSIMULINKAPPLICATION
InthisproblemwewillfirstaskMatlabtoconvertthetransferfunctionasshownin
FigureE31usingthefollowingcommand:
>>[A,B,C,D]=tf2ss(1,[2,0.7,1])
NOTE:Youareencouragedtoreadthehelpfileontf2ssfunction(>>
helptf2ss).
Matlab'sanswers:
Now, let's get back to SIMULINK window and construct the necessary blocks as
shownbelow.Notethattheadditionalblocks(TransferFcnandits"scope")shown
in light blue are provided for comparison with the the output from statespace
block.
http://edu.levitas.net/Tutorials/Matlab/Simulink/examples.html
9/11
4/4/2016
SimulinkTUTORIALbyT.Nguyen
WARNING:Caresmustbetakeninselectingtheproperpulseduration.Aduration
that is too short may yield computational error. A duration that is too long could
misrepresentthedynamicsofthemodeledsystem.
http://edu.levitas.net/Tutorials/Matlab/Simulink/examples.html
10/11
4/4/2016
SimulinkTUTORIALbyT.Nguyen
Torunthesimulationusekeystrokes:CTRL+Torclickonthe
button.
Tochangethesimulationparametersandmakeadjustmenttosimulationduration,
pressCTRL+EorchooseSimulationparameters...fromSimulationmenu.
Enter30forStoptime.
ThescreenshotbelowshowstheimpulseresponseofthesystemdescribedbyEq.2
withm=2k=1c=0.7
For the fun of it, you may want to make adjustments to damping ratio and/or
springstiffnessparamatersandrunthesimulationagaintoseehowthesechanges
wouldaffecttheresponsetotheimpulseinput.
_________________________________
Referencesandfurtherreadings:
1.Ogata,K.,ModernControlEngineering,3rd.Ed.,PrenticeHall,NJ,1997
2.Dorf,R.,Bishop,R.,ModernControlSystems,8thEd.,AddisonWesley,CA,1998
3.Mathworks'documentationsonSimulink
T.NguyenMMIII,MMIV,MMV,MMVI.Allrightsreserved.Republicationorredistributionofthe
contentinthissiteisexpresslyprohibitedwithoutthepriorwrittenconsentoftheauthor.
http://edu.levitas.net/Tutorials/Matlab/Simulink/examples.html
11/11