SimulinkTUTORIALbyT.Nguyen
|Matlab||ControlSystemsApplications||SymbolicCalculation||SideNotes||Aboutthissite|
SIMULINKEXAMPLES
Example1.SimulationofanEquation.
InthisexamplewewilluseSimulinktomodelanequation.Let'sconsider
(1)
>
M
E
N
U
where the displacement x is a function of time t, frequency w, phase angle phi, and
amplitue A. In this example the values for these parameters are set as follows:
frequency=5rad/secphase=pi/2A=2.
1.FromSimulink'slibrarydragthefollowingblockstotheModelWindow
>
Blockstobedraggedtothemodel WherelocatedinSimulinklibrarybrowser
window
Ramp
Sources
Constant
Sources
Gain
MathOperation
Sum
MathOperation
Product
MathOperation
TrigonometryFunction
MathOperation
Scope
Sinks
Mux
SignalRouting
2.ThenextstepistoconnecttheseblocksasshowninFigureE11.
http://edu.levitas.net/Tutorials/Matlab/Simulink/examples.html
1/12
1/29/2016
SimulinkTUTORIALbyT.Nguyen
FigureE11
Doubleclickontheblocksandentertheappropriatevaluesaspromptedbythepopup
dialogwindows.Notethatthecosinefunctioncanbeselectedfromthepulldownmenu
inthepopupwindow.Inthearrangementshownabove,theinputsignal(aramp
function)istobedisplayedalongwiththeoutput(displacement)viatheuseofthemux
toolasdemonstratedearlierinthistutorial.Toviewtheplots,doubleclickonthescope.
3.Makesureallblocksareconnectedcorrectlythenrunthesimulation(CTRL+T).You
mayneedtoselecttheAutoscalebutton
onthescopedisplaywindowtoobtaina
betterdisplayoftheplots.
Youmayfindthesinusoidalplotstobeabit"jaggy".Youmaywanttoimprovethe
resolutionofthedisplayedplotbyredefiningtheMaxStepSidevalue("auto"isseta
defaultvalue)inSimulationParameterswindow(withkeystrokesCTRL+Einthemodel
window).Justforfun,youmaywanttoexperiementwithdifferentchoiceofsolver.
ODE45isadefaultchoice.Youareencouragedtolearnmoreaboutthesolvermethods
bycheckingoutthehelpfilesinMatlabcommandwindow.Forinstance,helpODE45for
parametersinnonstiffdifferentialequations.
ThisexamplehasdemonstratedtheuseSimulinkwithbuiltinmathematicalfunctions
andothersupportingtoolboxestosimulateanequation.Thesameoutput/resultcanalso
beobtainedwiththefollowingsetofinstructionsenteredinMatlabcommandwindow:
>>t=(0:.01:10)A=2phi=pi/2omega=5
>>xt=A*cos(omega*t+phi)
>>plot(t,xt)grid
______________________________________
Example2.MassSpringDashpotSystemSimulation
ConsideramassspringdashpotsystemasshowninFigureE21.The
mathematicalmodelforthissystemisdescribedby
(2)
wheremistheequivalentmassofthesystem,cisthedampingratio,
k is the spring stiffness, and f(t) is the forcing function in the x
direction.
FigureE21
STEP1
InSimulink,createanewmodelwindow(CTRL+N)anddragthefollowing
blocksfromtheSimulinklibrarywindow:
Blockstobedraggedtothe WherelocatedinSimulinklibrarybrowser
modelwindow
Step
Sources
Gain
MathOperation
Sum
MathOperation
Integrator
Continuous
Scope
Sinks
http://edu.levitas.net/Tutorials/Matlab/Simulink/examples.html
2/12
1/29/2016
SimulinkTUTORIALbyT.Nguyen
ToWorkspace
Sinks
STEP2
ByrearrangingEqn2toyieldanexpressionfortheaccelerationterm,
Eqn(2)becomes
(3)
BasedonEqn3,weconnecttheblocksinthediagramasshowninFigure
E22.UseCTRL+FandCTRL+Rtoflipandrotatetheblocksasnecessary
(selecttheblockfirstthenexecutethekeysequence).Notethatyoucan
useCTRL+rightmousebuttontocreatebranchesoftheconnectinglines.
Don'tworryabouttheparametervaluesandthesignsfortheseblocksat
thispointaswe'lltakecareofthisinSTEP3.Justgetthemconnected
first.
FigureE22
STEP3
Enterthevaluesoftheparametersforeachblock.Inthisexample,wewill
setm=2.0c=0.7k=1.Youareencouragedtotrydifferentvaluesand
observethesystem'sresponsetostepinput.
Toshowthatyoumayobtaindifferentformofoutput,Iincludedanother
block(inadditiontothescopeblock)called"simout".Thisblockcanbe
foundintheSinksgroupfromtheSimulinkLibrarybrowser.Theoutput
fromthisblockisusedinMatlabworkspace.Toillustratehowthisblock
works,Iwillselectanamefortheoutputcalled"simout"asthevariable
nameintheblock'sparametersetting(doubleclickonthe"simput"block
tobringuptheparameterdialogwindow).Inadditon,Iwillneedatime
arrayfromthesimulation.Thiscanbespecifedasaparameterinthe
SimulationParameterwindow(CTRL+E)undertheWorkspaceI/Otabas
showninFigureE23.
http://edu.levitas.net/Tutorials/Matlab/Simulink/examples.html
3/12
1/29/2016
SimulinkTUTORIALbyT.Nguyen
FigureE23
STEP4
Runthesimulationbyclickingonthe
button(alternatelyyoumayuse
keyboardcommandCTRL+T).Thescreenshotoftheoutputfromthe
ScopeblockisshowinFigureE23.
FigureE23
That'sit!Youhavesuccessfullymodeledandsimulatedasecondorder
underdampeddynamicsystem.Toexamdifferentresponses,feelfreeto
changedifferentvaluesform,c,andkinthegainblocks.
Toseehowyoucanusetheoutputfromthe"simout"block(bytheway,
youmaynametheblockwhateveryouwish),gotoMatlabCommand
windowandtype
>>who
YoushouldreceiveanechofromMatlablistingthefollowingvariables:
"simout"and"time"(andperhapsothersvariablesinthecurrent
workspacememory).
Now,youmaycreateaplotofthesystemresponseidenticaltothat
shownintheScopeoutput.Thecommandforcreatingthisplotis:
>>plot(time,simout)grid
http://edu.levitas.net/Tutorials/Matlab/Simulink/examples.html
4/12
1/29/2016
SimulinkTUTORIALbyT.Nguyen
Notethattheoutoutformatusedintheexampleaboveismatrixtype.
Theoutputsenttoworkspacecanbeusedforfurtheranalysisandstorage
inasciiformat.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
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.
http://edu.levitas.net/Tutorials/Matlab/Simulink/examples.html
5/12
1/29/2016
SimulinkTUTORIALbyT.Nguyen
FigureE32
ClickOKtoclosethedialog.DoubleclickontheSaveOutputToAFileblockto
openthedialogwindowasshowninFigureE33.IntheFilenameboxspecify
thepathandthenameofthefileyouwishtosave.Thesavedfilewillbein
.MATformat(yes,it'sinbinaryformat!Sodon'ttrytoreadit).Youwillbeable
toloadthisfiletoMatlabworkspacelateron.Makesuretorememberwhereyou
savethefileto.Inthisexample,I'llputthefileinmyDdriveunder"temp"
directoryandnamethefile"example3out.mat".Youmaychooseother
convenientlocationonyourcomputer.
In the Variable name box, enter a name of your choice. Here I name the
variable"simout".
Leaveotherparametersindefautsettingsunlessyouwishtoobtainmoreplot
pointsbychangingtheSampleTimesetting.
FigureE33
STEP Runthesimulationbyclickingonthebutton(alternatelyyoumayusekeyboard
4
commandCTRL+T).ThescreenshotoftheoutputfromtheScopeblockisshow
inFigureE34.
FigureE34
NowbycomparingFigureE23andFigureE34youwillseethatthereponses
http://edu.levitas.net/Tutorials/Matlab/Simulink/examples.html
6/12
1/29/2016
SimulinkTUTORIALbyT.Nguyen
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
specify the full path in the load command, e.g., >>load
D:/temp/example3out.mat.
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.
http://edu.levitas.net/Tutorials/Matlab/Simulink/examples.html
7/12
1/29/2016
SimulinkTUTORIALbyT.Nguyen
____________________________________________________________
Example4.
Inthisexample,we'llconsiderthesamesystemasdescribedinExample3.But
insteadofusingstepinput,we'llexcitethesecondordersystemwithimpulseload.In
addition,wewillsimulatetheresponseusingastatespacemodel.
NOTESONIMPULSEFUNCTION
Impulse function is useful in the simulatoin of impact or sudden loads such as the
strikingofathetipofthepoleagainstaballinapoolgame.Unitimpulsefunctionata
desiredinstantaisdefinedby
(4)
Equation4isalsoknownasDiracdeltafunction.
TosimulateunitimpulseinSimulink,we'lluseatwoblockstepfunctionsetasshown
below.
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 future
stateofthesystem.Mathematically,thestateofthesystemisdescribedbyasetof
firstorderdifferentialequationintermsofstatevariables.
Forourexample,wewillexpressthenaturalstatevariables,e.g.,positionandvelocity,
ofthesystemintermsofthefollowingvariables:
(5)
(6)
Inamatrixform:
http://edu.levitas.net/Tutorials/Matlab/Simulink/examples.html
8/12
1/29/2016
SimulinkTUTORIALbyT.Nguyen
(7)
Equation7maybeexpressedinamorecompactform:
(8)
whereAisknownasthesystemmatrixandBastheinputmatrix.
Theoutputequationisexpressedby
(9)
where
(10)
and
(11)
CiscalledtheoutputmatrixandDiscalledthedirecttransmittancematrix.
MATLABANDSIMULINKAPPLICATION
In this problem we will first ask Matlab to convert the transfer function as shown in
FigureE31usingthefollowingcommand:
>>[A,B,C,D]=tf2ss(1,[2,0.7,1])
NOTE: You are encouraged to read the help file on tf2ss function (>>
helptf2ss).
Matlab'sanswers:
http://edu.levitas.net/Tutorials/Matlab/Simulink/examples.html
9/12
1/29/2016
SimulinkTUTORIALbyT.Nguyen
Now,let'sgetbacktoSIMULINKwindowandconstructthenecessaryblocksasshown
below. Note that the additional blocks (Transfer Fcn and its "scope") shown in light
blueareprovidedforcomparisonwiththetheoutputfromstatespaceblock.
Asdemonstratedinpreviousexamples,youmaychangetheparametersinthestate
spaceblockoranyotherblockbydoubleclickingonittobringupaparameterediting
window.
Forstatespacemodel,enterthefollowingparameters:
A:[0.350.510]
B:[10]
C:[00.5]
D:0
Once the entries are completed, click OK button to close the panel and continue on
makingnecessaryentriesforotherblocks.
Fortheimpulsesimulation:
In this example, let's consider an unit impulse at 0.2 second with pulse duration of
0.01secondandamagnitudeof40.Tosimulatethisimpulse,we'llenterinthefirst
block(Stepstart)thefollowingparameters(doubleclickontheblocktobringupthe
http://edu.levitas.net/Tutorials/Matlab/Simulink/examples.html
10/12
1/29/2016
SimulinkTUTORIALbyT.Nguyen
parameterwindows):
Steptime:0.2
Initialvalue:0
Finalvalue:40
Forthesecondblock(Stepend):
Steptime:0.21
Initialvalue:0
Finalvalue:40
Thiswillproducethefollowingimpulse:
WARNING:Caresmustbetakeninselectingtheproperpulseduration.Adurationthat
is too short may yield computational error. A duration that is too long could
misrepresentthedynamicsofthemodeledsystem.
Torunthesimulationusekeystrokes:CTRL+Torclickonthe
button.
Forthefunofit,youmaywanttomakeadjustmentstodampingratioand/orspring
stiffness paramaters and run the simulation again to see how these changes would
http://edu.levitas.net/Tutorials/Matlab/Simulink/examples.html
11/12
1/29/2016
SimulinkTUTORIALbyT.Nguyen
affecttheresponsetotheimpulseinput.
_________________________________
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
12/12