matlab - HiT.no
UniversityCollegeofSoutheastNorway
MATLAB
PartIII:SimulinkandAdvancedTopics
Hans-PetterHalvorsen,2016.10.04
http://home.hit.no/~hansha
Preface
CopyrightYoucannotdistributeorcopythisdocumentwithoutpermissionfromtheauthor.
Youcannotcopyorlinktothisdocumentdirectlyfromothersources,webpages,etc.You
shouldalwayslinktotheproperwebpagewherethisdocumentislocated,typically
http://home.hit.no/~hansha/…
InthisMATLABCourseyouwilllearnbasicMATLABandhowtouseMATLABinControland
Simulationapplications.AnintroductiontoSimulinkandotherToolswillalsobegiven.
MATLABisatoolfortechnicalcomputing,computationandvisualizationinanintegrated
environment.MATLABisanabbreviationforMATrixLABoratory,soitiswellsuitedfor
matrixmanipulationandproblemsolvingrelatedtoLinearAlgebra, Modelling,Simulation
andControlapplications.
Thisisaself-pacedcoursebasedonthisdocumentandsomeshortvideosontheway.This
documentcontainslotsofexamplesandself-pacedtasksthattheuserswillgothroughand
solveontheirown.Theusermaygothroughthetasksinthisdocumentintheirownpace
andtheinstructorwillbeavailableforguidancethroughoutthecourse.
TheMATLABCourseconsistsof3parts:
•
•
•
MATLABCourse–PartI:IntroductiontoMATLAB
MATLABCourse–PartII:Modelling,SimulationandControl MATLABCourse–PartIII:SimulinkandAdvancedTopics
InPartIIIofthecourse(PartIII:AdvancedTopics,SimulinkandotherTools)youwilllearn
howtousesomeofthemoreadvancedfeaturesinMATLAB.Wewillalsotakeacloserlook
atSimulink,whichisaBlockDiagramSimulationToolusedtogetherwithMATLAB.Wewill
alsogiveanoverviewtoothertoolsfornumericalmathematicsandsimulation.
YoumustgothroughMATLABCourse–PartI:IntroductiontoMATLABbeforeyoustart.
ThecourseconsistsoflotsofTasksyoushouldsolvewhilereadingthiscoursemanualand
watchingthevideosreferredtointhetext.
ii
Makesuretobringyourheadphonesforthevideosinthiscourse.Thecourse
consistsofseveralshortvideosthatwillgiveyouanintroductiontothedifferenttopicsin
thecourse.
Prerequisites:Youshouldbefamiliarwithundergraduate-levelmathematicsandhave
experiencewithbasiccomputeroperations.
WhatisMATLAB?
MATLABisatoolfortechnicalcomputing,computationandvisualizationinanintegrated
environment.MATLABisanabbreviationforMATrixLABoratory,soitiswellsuitedfor
matrixmanipulationandproblemsolvingrelatedtoLinearAlgebra.
MATLABisdevelopedbyTheMathWorks.MATLABisashort-termforMATrixLABoratory.
MATLABisinuseworld-widebyresearchersanduniversities.
Formoreinformation,seewww.mathworks.com
WhatisSimulink?
MATLABofferslotsofadditionalToolboxesfordifferentareassuchasControlDesign,Image
Processing,DigitalSignalProcessing,etc.
Simulink,developedbyTheMathWorks,isacommercialtoolformodeling,simulatingand
analyzingdynamicsystems.Itsprimaryinterfaceisagraphicalblockdiagrammingtoolanda
customizablesetofblocklibraries.ItofferstightintegrationwiththerestoftheMATLAB
environmentandcaneitherdriveMATLABorbescriptedfromit.Simulinkiswidelyusedin
controltheoryanddigitalsignalprocessingforsimulationanddesign.
ThistrainingwillgiveyouthebasicknowledgeofSimulinkandhowyoucanuseittogether
withMATLAB.
OnlineMATLABResources:
MATLABBasics: http://home.hit.no/~hansha/video/matlab_basics.php iii
Modelling,SimulationandControlwithMATLAB:
http://home.hit.no/~hansha/video/matlab_mic.php MATLABTraining:
http://home.hit.no/~hansha/documents/lab/Lab%20Work/matlabtraining.htm MATLABforStudents:
http://home.hit.no/~hansha/documents/lab/Lab%20Work/matlab.htm
Onthesewebpagesyoufindvideosolutions,completestepbystepsolutions,downloadable
MATLABcode,additionalresources,etc. iv
TableofContents
Preface......................................................................................................................................ii
TableofContents......................................................................................................................v
1
Introduction......................................................................................................................1
2
Simulink.............................................................................................................................2
2.1
StartusingSimulink...................................................................................................2
2.1.1
BlockLibraries...................................................................................................4
2.1.2
CreateanewModel..........................................................................................6
2.2
Wiringtechniques.....................................................................................................7
2.3
HelpWindow.............................................................................................................8
2.4
Configuration...........................................................................................................10
2.5
Examples.................................................................................................................11
Task1: SimulationinSimulink–BacteriaPopulation..............................................19
2.6
Data-drivenModelling.............................................................................................20
2.6.1
UsingtheCommandwindow..........................................................................21
2.6.2
Usingam-file...................................................................................................23
2.6.3
SimulationCommands.....................................................................................24
Task2: Mass-Spring-DamperSystem......................................................................25
Task3: SimulinkSimulation.....................................................................................27
3
DebugginginMATLAB.....................................................................................................29
3.1
TheDebuggingProcess...........................................................................................31
Task4: Debugging....................................................................................................32
4
MoreaboutFunctions.....................................................................................................34
v
vi
4.1
TableofContents GettingtheInputandOutputArguments...............................................................34
Task5: CreateaFunction........................................................................................35
Task6: OptionalInputs:Usingnarginandnargchk.................................................36
Task7: OptionalOutputs:Usingnargoutandnargoutchk......................................36
5
MoreaboutPlots.............................................................................................................38
5.1
LaTEXorTEXCommands.........................................................................................38
Task8: LATEXCommands........................................................................................39
Task9: 3DPlot.........................................................................................................39
6
UsingCellsintheMATLABEditor....................................................................................41
Task10:
7
ImportingData................................................................................................................43
Task11:
8
ImportData.............................................................................................45
StructuresandCellArrays...............................................................................................46
8.1
Structures................................................................................................................46
Task12:
9
UsingCells................................................................................................42
UsingStructures......................................................................................46
AlternativestoMATLAB..................................................................................................47
9.1
Octave.....................................................................................................................47
9.2
ScilabandScicos......................................................................................................47
9.3
LabVIEWMathScript................................................................................................48
9.3.1
HowdoyoustartusingMathScript?...............................................................49
9.3.2
Functions.........................................................................................................49
9.3.3
ODESolversinMathScript...............................................................................50
9.4
LabVIEW..................................................................................................................51
9.4.1
TheLabVIEWEnvironment..............................................................................51
9.4.2
FrontPanel......................................................................................................52
9.4.3
BlockDiagram..................................................................................................55
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
vii
9.4.4
9.5
TableofContents LabVIEWControlDesignandSimulationModule...........................................56
MathematicsinLabVIEW........................................................................................60
9.5.1
BasicMath.......................................................................................................61
9.5.2
LinearAlgebra..................................................................................................62
9.5.3
CurveFitting....................................................................................................63
9.5.4
Interpolation....................................................................................................63
9.5.5
IntegrationandDifferentiation.......................................................................64
9.5.6
Statistics..........................................................................................................64
9.5.7
Optimization....................................................................................................65
9.5.8
DifferentialEquations(ODEs)..........................................................................65
9.5.9
Polynomials.....................................................................................................66
9.6
MATLABIntegration(MATLABScript)inLabVIEW..................................................66
9.7
Python.....................................................................................................................67
AppendixA–MathScriptFunctions........................................................................................69
AppendixB:Mathematicscharacters.....................................................................................71
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
1 Introduction
Part3:AdvancedTopics,SimulinkandotherToolsconsistsofthefollowingtopics:
•
•
•
IntroductiontoSimulink
AdvancedTopicsinMATLAB:
o DebugginginMATLAB
o Moreaboutfunctions
o MoreaboutPlots
o UsingCellsintheMATLABEditor
o ImportingData
o StructuresandCellArrays
AlternativestoMATLAB
1
2 Simulink
Simulinkisanenvironmentforsimulationandmodel-baseddesignfordynamicand
embeddedsystems.Itprovidesaninteractivegraphicalenvironmentandacustomizableset
ofblocklibrariesthatletyoudesign,simulate,implement,andtestavarietyoftime-varying
systems,includingcommunications,controls,signalprocessing,videoprocessing,andimage
processing.
Simulinkoffers:
•
•
Aquickwayofdevelopyourmodelincontrasttotextbased-programminglanguage
suchase.g.,C.
Simulinkhasintegratedsolvers.Intextbased-programminglanguagesuchase.g.,C
youneedtowriteyourownsolver.
GraphicalProgramming:InSimulinkyouprograminagraphicalway.LabVIEWisanother
programminglanguagewhereyouusegraphicalprogramminginsteadoftext-based
programming.LabVIEWisdevelopedbyNationalInstruments.YouwilluseLabVIEWina
laterchapter
Beforeyoustart,youshouldwatchthefollowingvideos:
•
•
“SimulinkOverview”
“GettingStartedwithSimulink”
Thevideosisavailablefrom:http://home.hit.no/~hansha/?training=matlab 2.1 StartusingSimulink
YoustartSimulinkfromtheMATLABIDE:
OpenMATLABandselecttheSimulinkiconintheToolbar:
2
3
Simulink Ortype“simulink”intheCommandwindow,likethis:
Thenthefollowingwindowappears(SimulinkLibraryBrowser):
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
4
Simulink TheSimulinkLibraryBrowseristhelibrarywhereyoufindalltheblocksyoumayusein
Simulink.Simulinksoftwareincludesanextensivelibraryoffunctionscommonlyusedin
modelingasystem.Theseinclude:
•
•
•
Continuousanddiscretedynamicsblocks,suchasIntegration,Transferfunctions,
TransportDelay,etc.
Mathblocks,suchasSum,Product,Add,etc
Sources,suchasRamp,RandomGenerator,Step,etc
2.1.1
BlockLibraries
HerearesomecommonusedContinuousBlocks:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
5
HerearesomecommonusedMathOperationsBlocks:
HerearesomecommonusedSignalRoutingBlocks:
HerearesomecommonusedSinksBlocks:
HerearesomecommonusedSourcesBlocks:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
Simulink 6
Simulink InadditiontherearelotsofblockindifferentToolboxes:
2.1.2
CreateanewModel
ClicktheNewiconontheToolbarinordertocreateanewSimulinkmodel:
Thefollowingwindowappears:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
7
Simulink YoumaynowdragtheblocksyouwanttousefromtheSimulinkLibraryBrowsertothe
modelsurface(orright-clickonablockandselect“Addto…”).
Example:
Inthisexampleweplace(draganddrop)toblocks,aSineWaveandaScope,onthemodel
surface:
2.2 Wiringtechniques
Usethemousetowiretheinputsandoutputsofthedifferentblocks.Inputsarelocatedon
theleftsideoftheblocks,whileoutputsarelocatedontherightsideoftheblocks.
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
8
Simulink Whenholdingthemouseoveraninputoranoutputthemousechangestothefollowing
symbol.
Usethemouse,whileholdingtheleftbuttondown,todragwiresfromtheinputtothe
output.
AutomaticBlockConnection:
Anotherwiringtechniqueistoselectthesourceblock,thenholddowntheCtrlkeywhile
left-clickingonthedestinationblock.
Trythedifferenttechniquesontheexampleabove.
Connectionfromawiretoanotherblock
Ifwireaconnectionfromawiretoanotherblock,liketheexamplebelow,youneedtohold
downtheCtrlkeywhileleft-clickingonthewireandthentotheinputofthedesiredblock.
2.3 HelpWindow
Inordertoseedetailedinformationaboutthedifferentblocks,usethebuilt-inHelpsystem.
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
9
Simulink AllstandardblocksinSimulinkhavedetailedHelp.ClicktheHelpbuttonintheBlock
Parameterwindowforthespecificblockinordertogetdetailedhelpforthatblock.
TheHelpWindowthenappearswithdetailedinformationabouttheselectedblock: MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
10
Simulink 2.4 Configuration
Therearelotsofparametersyoumaywanttoconfigureregardingyoursimulation.Select
“ConfigurationParameters…”intheSimulationmenu.
Thefollowingwindowappears:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
11
Simulink Hereyousetimportantparameterssuchas:
•
•
•
StartandStoptimeforthesimulation
WhatkindofSolvertobeused(ode45,ode23etc.)
Fixed-step/Variable-step
Note!EachofthecontrolsontheConfigurationParametersdialogboxcorrespondstoa
configurationparameterthatyoucansetviathe“sim”and“simset”commands.Youwill
learnmoreaboutthesecommandslater.
Solversarenumericalintegrationalgorithmsthatcomputethesystemdynamicsovertime
usinginformationcontainedinthemodel.Simulinkprovidessolverstosupportthe
simulationofabroadrangeofsystems,includingcontinuous-time(analog),discrete-time
(digital),hybrid(mixed-signal),andmultiratesystemsofanysize.
2.5 Examples
Belowwewillgothroughsomeexamplesinordertoillustratehowtocreateblockdiagrams
andrelatedfunctionality.
Example:
Integratorwithinitialvalue
Createthefollowingmodel(anintegrator)andrunthesimulation:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
12
Simulink Step1:Placetheblocksonthemodelsurface
Thisexampleusethefollowingblocks:
Step2:Configuration
Double-clickontheIntegratorblock.TheParameterwindowfortheIntegratorblock
appears:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
13
Simulink Select“Initialconditionsource=external”.TheIntegratorblocknowlookslikethis:
Double-clickontheConstantblock.TheParameterwindowfortheConstantblockappears:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
14
Simulink IntheConstantvaluefieldwetypeintheinitialvaluefortheintegrator,e.g.,typethevalue
1.
Step3:Wiring
Usethemousetowiretheinputsandoutputsofthedifferentblocks.
Whenholdingthemouseoveraninputoranoutputthemousechangetothefollowing
symbol.
DrawawirebetweentheoutputontheConstantblocktothelowerinputintheIntegrator
block,likethis: Youcouldalsodolikethis:
Wiretherestoftheblockstogetherandyouwillgetthefollowingdiagram:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
15
Simulink Step4:Simulation
Startthesimulationbyclickingthe“StartSimulation”iconintheToolbar:
Step5:TheResults
Double-clickintheScopeblockinordertoseethesimulatedresult:
Example:
SineWave
Createtheblockdiagramasshownbelow:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
16
Simulink SetthefollowingparameterfortheIntegratorblock:
Theresultshouldbelikethis:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
17
Simulink Example:
Usingvectors
Createthefollowingblockdiagram:
FortheGainblock,typethefollowingparameters:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
18
Simulink Asyousee,wecanusestandardMATLABsyntaxtocreateavector.
Ifyouwanttoseethesignaldimensions,select“SignalDimensions”and“WideNonscalar
Lines”asshownhere:
Theblockdiagramshouldnowlooklikethis:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
19
Simulink Thethicklinesindicatevectors,whilethenumber(8)isthesizeofthevector.
Let’schangetheSaturationblock:
AsyouseeyoumayusestandardMATLABfunctionsandsyntax.
RunthesimulationandseetheresultsintheScopeblock.
Task1:
SimulationinSimulink–BacteriaPopulation
Inthistaskwewillsimulateasimplemodelofabacteriapopulationinajar(knownfroma
previoustask).
Themodelisasfollows:
birthrate=bx
deathrate=px2
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
20
Simulink Thenthetotalrateofchangeofbacteriapopulationis:
𝑥 = 𝑏𝑥 − 𝑝𝑥 2 Setb=1/hourandp=0.5bacteria-hour
Wewillsimulatethenumberofbacteriainthejarafter1hour,assumingthatinitiallythere
are100bacteriapresent.
Procedure:
1.
2.
3.
4.
Createtheblockdiagramforthesystemusing“pen&paper”
StartSimulinkandcreateaNewModel
DraginthenecessaryblocksfromtheSimulinkLibraryBrowser
Configurethedifferentblocks(double-click/right-clickdependingonwhatyouneed).
Someblocksneedtobe“flipped”(Right-click→Format→FlipBlock),whileinother
blocksyouneedtosetavalue(double-click)
5. Drawlinesbetweenthedifferentblocksusingthemouse
6. SetSimulationSettings(Simulation→ConfigurationParameters).Thesimulation
Time(StopTime)shouldbesetto1(hour)
7. UseaScopetoseetheSimulatedResult
Youwillneedthefollowingblocks:
•
Integratorblock
Tosolvethedifferentialequation.Note!Initialvaluex0=100
•
TwoGainblocks
Forp(=0.5)andb(=1)
•
Productblock
•
Sumblock
•
Scopeblock
Tocomputex2
Note!Oneplus(+)mustbechangedtominus(-)
Toshowthesimulatedresult.Note!SettoAutoscale [EndofTask]
2.6 Data-drivenModelling
YoumayuseSimulinktogetherwithMATLABinordertospecifydataandparameterstoyour
Simulinkmodel.YoumayspecifycommandsintheMATLABCommandWindoworas
commandsinanm-file.Thisiscalleddata-drivenmodeling.
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
21
2.6.1
Simulink UsingtheCommandwindow
Example:
Giventhefollowingsystem:
Note!Inordertoget3inputsontheScopeblock:
Double-clickontheScopeandselecttheParametersiconintheToolbar:
ThenselectNumberofAxes=3:
Configurethezero-orderholdblockslikethis:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
22
Simulink WritethefollowingintheCommandwindowinMATLAB:
RuntheSimulinkmodelfromtheSimulink:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
23
Simulink Wethengetthefollowingresults:
2.6.2
Usingam-file
ItisgoodpracticetobuildyourmodelinSimulinkandconfigureandrunthesimulationfrom
aMATLABm-file.
ATypicalm-filecouldlooklikethis:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
24
Simulink Youusethesimsetcommandtoconfigureyoursimulationparametersandthesim
commandtorunthesimulation.
Thevariablesyourefertointhem-fileissetintheConstantvaluefieldintheParameter
windowforeachblock.
2.6.3
SimulationCommands
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
25
Simulink Themostusedcommandis:
•
•
simset
sim
UsethesecommandsifyouconfigureandrunyourSimulinkmodelfromam-file.
Example:
%Simulator Settings
t_stop=100; %[s]
T_s=t_stop/1000; %[s]
options=simset('solver', 'ode5', 'fixedstep', T_s);
%Starting simulation
sim('mass_spring_damper', t_stop, options);
[EndofExample]
Task2:
Mass-Spring-DamperSystem
Inthisexamplewewillcreateamass-spring-dampermodelinSimulinkandconfigureand
runthesimulationfromaMATLABm-file.
Inthisexerciseyouwillconstructasimulationdiagramthatrepresentsthebehaviorofa
dynamicsystem.Youwillsimulateaspring-massdampersystem.
𝐹(𝑡) − 𝑐𝑥(𝑡) − 𝑘𝑥(𝑡) = 𝑚𝑥(𝑡)
wheretisthesimulationtime,F(t)isanexternalforceappliedtothesystem,cisthe
dampingconstantofthespring,kisthestiffnessofthespring,misamass,andx(t)isthe
positionofthemass. 𝑥 isthefirstderivativeoftheposition,whichequalsthevelocityof
themass. 𝑥 isthesecondderivativeoftheposition,whichequalstheaccelerationofthe
mass.
Thefollowingfigureshowsthisdynamicsystem.
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
26
Simulink Thegoalistoviewthepositionx(t)ofthemassmwithrespecttotimet.Youcancalculate
thepositionbyintegratingthevelocityofthemass.Youcancalculatethevelocityby
integratingtheaccelerationofthemass.Ifyouknowtheforceandmass,youcancalculate
thisaccelerationbyusingNewton'sSecondLawofMotion,givenbythefollowingequation:
Force=Mass×Acceleration
Therefore, Acceleration=Force/Mass
Substitutingtermsfromthedifferentialequationaboveyieldsthefollowingequation:
𝑥=
1
(𝐹 − 𝑐𝑥 − 𝑘𝑥) 𝑚
Youwillconstructasimulationdiagramthatiteratesthefollowingstepsoveraperiodof
time.
→Createtheblockdiagramforthemass-spring-dampermodelabove.
Insteadofhard-codingthemodelparametersintheblocksyoushouldrefertothemas
variablessetinanm-file.
Thesevariablesshouldbeconfigured:
•
•
x_init
dxdt_init
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
27
•
•
•
•
•
•
Simulink m=
c=
k
t_step_F
F_O
F_1
m-File
Thefollowingvariablesshouldthenbesetinthem-file:
x_init=4; %[m]. Initial position.
dxdt_init=0; %[m/s]. Initial Speed.
m=20; %[kg]
c=4; %[N/(m/s)]
k=2; %[N/m]
t_step_F=50; %[s]
F_O=0; %[N]
F_1=4; %[N]
→CreatethemodelofthesysteminSimulink,andthencreateam-filewhereyouspecify
modelandsimulationparameters.Thenusethesimfunctioninordertorunthesimulation
withinthem-file. Watchthefollowingvideoifyouneedassistant“SimulinkQuickie!”byFinnHaugen.
Thevideoisavailablefrom:http://home.hit.no/~hansha/?training=matlab [EndofTask]
Task3:
SimulinkSimulation
Giventheautonomoussystem:
𝑥 = 𝑎𝑥
<
where 𝑎 = − ,where 𝑇 isthetimeconstant
=
Thesolutionforthedifferentialequationisfoundtobe:
𝑥 𝑡 = 𝑒 @A 𝑥B Set 𝑇 = 5andtheinitialcondition 𝑥(0) = 1.
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
28
Simulink SimulatethesysteminSimulinkwhereweplotthesolution 𝑥(𝑡) inthetimeinterval 0 ≤
𝑡 ≤ 25
[EndofTask]
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
3 DebugginginMATLAB
Debuggingisaboutdifferenttechniquesforfindingbugs(errorsthatmakeyourcodenot
workasexpected)inyourcode.
Inallbutthesimplestprograms,youarelikelytoencountersometypeofunexpected
behaviorwhenyouruntheprogramforthefirsttime.Programdefectscanshowupinthe
formofwarningorerrormessagesdisplayedinthecommandwindow,programsthathang
(neverterminate),inaccurateresults,orsomenumberofothersymptoms. Itisdifficulttowritecodewithouterrors(bugs),butMATLABhavepowerfulDebugging
functionality,similartoothertoolslike,e.g.,VisualStudio.
Whywecallitdebugging?Theyfoundabug(actuallyamoth)insideacomputerin1947that
madetheprogramnotbehavingasexpected.Thiswasthe“first”realbugwhichwas
debugged.
Step1:RemovingWarningsandErrorsnotifiedbyMATLAB
Thefirststepinordertoavoiderrorsistoremoveallwarningsanderrorsnotifiesby
MATLABintheEditor.OntherightsideoftheEditortherewillbeshownsymbolsto
illustratethatMATLABhavefoundpotentialerrorsinyourcode.
Warnings-Clickthe
symbolstogetmoreinformationaboutaspecificwarning
Example:
29
30
DebugginginMATLAB Errors-Clickthe
symbolstogetmoreinformationaboutaspecificerror
Example:
→TakenecessaryactionsinordertoremovetheseErrorsandWarnings!
Step2:UsingDebuggingToolsandTechniquesintheMATLABEditor
InadditionMATLABhavemoresophisticateddebuggingtoolswewilllearnmoreabout
below.Thesearetoolsyouusewhenyourprogramisrunning.
BelowweseethebasicdebuggingfunctionalityinMATLAB:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
31
DebugginginMATLAB TheMATLABDebuggerenablesyoutoexaminetheinnerworkingsofyourprogramwhile
yourunit.Youcanstoptheexecutionofyourprogramatanypointandthencontinuefrom
thatpoint,steppingthroughthecodelinebylineandexaminingtheresultsofeach
operationperformed.YouhavethechoiceofoperatingthedebuggerfromtheEditor
windowthatdisplaysyourprogram,fromtheMATLABcommandline,orboth.
3.1 TheDebuggingProcess
Youcanstepthroughtheprogramrightfromthestartifyouwant.Forlongerprograms,you
willprobablysavetimebystoppingtheprogramsomewhereinthemiddleandstepping
throughfromthere.Youcandothisbyapproximatingwheretheprogramcodebreaksand
settingastoppingpoint(orbreakpoint)atthatline.Onceabreakpointhasbeenset,start
yourprogram.TheMATLABEditor/Debuggerwindowwillshowagreenarrowpointingto
thenextlinetoexecute.Fromthispoint,youcanexamineanyvaluespassedintothe
program,ortheresultsofeachoperationperformed.Youcanstepthroughtheprogramline
bylinetoseewhichpathistakenandwhy.Youcanstepintoanyfunctionsthatyour
programcalls,orchoosetostepoverthemandjustseetheendresults.Youcanalsomodify
thevaluesassignedtoavariableandseehowthataffectstheoutcome.
Whentheprogramisindebug-mode,thecommandpromptischangedto“K>>”andthe
followingmessageappearsinthestatusbar:
Yourcodecouldlooksomethinglikethis:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
32
DebugginginMATLAB Aredcircleindicatesthatyouhavesetabreakpoint,whichmeansyourprogramwill
stopatthisplaceinyourcodeandwaitforfurtherinstructionsfromyou. Thegreenarrowindicatesatwhatlineyourprogramisatthemoment.
Nowyoucanusethe“debuggingtoolbar”tostepthroughyourcode:
The“debuggingtoolbar”containsthefollowingbuttons:
Set/ClearBreakpoint
ClearallBreakpoints
Stepthroughtheprogram,linebyline
Stepin(toafunction,etc.)
Stepout(ofafunction,etc.)
Continue
ExitDebugmode
Task4:
Debugging
Createasimilarprogramlikethis:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
33
DebugginginMATLAB SetaBreakpointinsidetheloopandusetheDebuggingfunctionalitytostepthroughthe
programandwatchtheresultineachiteration.
Testallthedifferentbuttonsinthe“debuggingtoolbar”:
Inadditionyoushouldopensomeofyourpreviousprogramsyouhavemade,andtrythe
debuggingtoolsonthem.
[EndofTask]
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
4 MoreaboutFunctions
4.1 GettingtheInputandOutput
Arguments
Afunctionmayhaveseveralinputsandseveraloutputs.Usenarginandnargoutto
determinethenumberofinputandoutputargumentsinaparticularfunctioncall.Use
nargchkandnargoutchktoverifythatyourfunctioniscalledwiththerequirednumberof
inputandoutputarguments.
Example:
Wecreatethefollowingfunction:
function [x,y] = myfunc(a,b,c,d)
disp(nargchk(2,4,nargin)) % Allow 2 to 4 inputs
disp(nargoutchk(0,2,nargout)) % Allow 0 to 2 outputs
x = a + b;
y = a * b;
if nargin == 3
x = a + b + c;
y = a * b * c;
end
if nargin == 4
x = a + b + c + d;
y = a * b * c * d;
end
WetestthefunctionintheCommandwindowwithdifferentinputsandoutputs:
>> [x, y] = myfunc(1,2)
x =
3
y =
2
>> [x, y] = myfunc(1,2,3)
x =
6
y =
6
>> [x, y] = myfunc(1,2,3,4)
x =
34
35
MoreaboutFunctions 10
y =
24
>> [x] = myfunc(1,2)
x =
3
>> [x, y, z] = myfunc(1,2)
??? Error using ==> myfunc
Too many output arguments.
>> myfunc(1,2)
ans =
3
>>
Note!InnewerversionsofMATLAB,theerrorfunctionisrecommendedinsteadofthedisp
function,butbothshouldwork.
[EndofExample]
Task5:
CreateaFunction
You’vehaveprobablyexperiencedstandingontopofahillormountainandfeelinglikeyou
canseeforever.Howfarcanyoureallysee?Itdependsontheheightofthemountainand
theradiusoftheearth,asshowninthesketchbelow. Inthistaskwewillcreateafunctionthatfindsthedistancetothehorizon𝑥F .
YoumayusethePythagoreanlawtofind 𝑥F :
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
36
𝑅2 = 𝑥F2 = (𝑅 + ℎ)2 ⇔ 𝑥F =
MoreaboutFunctions ℎ 2𝑅 + ℎ 𝐷 isthediameteroftheearth, 𝑅 istheradiusoftheearth, ℎ isyourheightabovethe
earthstandingonamountain.Theradiusontheearthis 𝑅 = 6378𝑘𝑚.
→Createafunctionthatfindsxhfrominputparameterh, >>xh=horizon(h)
HowfarcanyouseeifyouareontopoftheMountEverest?
Makesurethefunctionmayhandlevectorinputsandcreateahelptextforthefunctionthat
describeswhatthefunctionisdoing.
→Createascriptwhereyouusethefunctiontoplothvs.xhwherehisavectorfrom1to
8000meters.Createlabels,titleandalegendintheplot.
[EndofTask]
Task6:
OptionalInputs:Usingnarginandnargchk
Thedistancetothehorizonisquitedifferentonthemoonthanontheearthbecausethe
radiusisdifferentforeach.
→ExtendyourfunctionsothatRcouldbeanoptionalinputtothefunction,e.g.:
>>xh=horizon(h,R)
Ifxh=horizon(h)isused,RisassumedtobeR=6378km(theearth).
→Usenargintosolvetheproblem.Usealsonargchktovalidatethenumberofinputs.
HowfarcouldyouseeifthemoonhadamountainsimilartoMountEverest?Theradiuson
themoonis 𝑅 = 1737𝑘𝑚.
[EndofTask]
Task7:
OptionalOutputs:Usingnargoutandnargoutchk
Letsaywealsomaywanttofindtheangle(a)betweenradiustothehorizonandthe
observer(youstandingontopofthemountain).Seetheillustrationabove.
→Extendyourfunctionsothattheangle 𝒂 couldbeanoptionaloutputfromthe
function,e.g.:
>>[xh,a]=horizon(h,R)
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
37
MoreaboutFunctions Ifxh=horizon(h,R)isused,ashouldbeignored(onlyxhiscalculated).
→Usenargouttosolvetheproblem.Usealsonargoutchktovalidatethenumberof
outputs.
Theangle 𝑎 isgivenby:
tan 𝑎 =
𝑥F
𝑥F
⇔ 𝑎 = atan
𝑅
𝑅
Note!Youhavetoconvertfromradianstodegrees(2𝜋 = 360S ).Useyourfunctionr2d
whichyoucreatedinaprevioustask.
[EndofTask]
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
5 MoreaboutPlots
MATLABhaveadvancePlotfunctionality.Wehavealreadyusedtheplotfunctionalityin
MATLABinadozensofexamples.Inthischapterwewilllearnmoreabouttheadvanced
plottingfunctionalitythatMATLABoffers.
5.1 LaTEXorTEXCommands
Whenusinglabels,legendsandtitlesinaplotyousometimeswantusemoreadvanced
labels,titles,legendsuchas:
“Solutionof
V
sin
<
𝑥 𝑑𝑥 ”
ThisisdonebyusingLaTeXorTeXcommands. InLaTeXtypesetting,mathematicalexpressionsarebracketedbythe$$symbol.Using$
bracketing,indicatesin-linemath.
Example:
TheMATLABcode:
legend({'$$\frac{-b \pm
'Interpreter', 'LaTeX')
\sqrt{b^{2}-4ac}}{2a}$$'},
title({'Equation: $\frac{-b
'Interpreter', 'LaTeX')
\pm
\sqrt{b^{2}-4ac}}{2a}$'},
givesthefollowingplot:
38
39
MoreaboutPlots [EndofExample]
SeeAppendixB:Mathematicscharacters.
Task8:
LATEXCommands
UseMATLABtocreatethefollowingplot:
[EndofTask]
Task9:
3DPlot
Useyourxh=horizon(h,R) fromaprevioustasktocreateameshplotwhereyouplot
xhfordifferentvaluesofhandRrespectively.
Tip!CallthefunctioninnestedForLoopsfordifferentvaluesforhandRrespectively.
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
40
MoreaboutPlots [EndofTask]
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
6 UsingCellsintheMATLAB
Editor
YoumaystructureMATLABcodeintheeditorbydefiningtextcells.Essentially,atextcellis
initiatedbyputtingthesymbol%%(double%character)inthefirstpositionofaline.The
cellendsonthelineprecedingthenext%%symbol.Afterthe%%symbol,aspaceshouldbe
inserted,followedbyadescriptivetext.TheMATLABEditormarksacellbyframingitwitha
yellowbox:whenyouputthecursorinacell,theframeisshown.Inorderforthistowork,
theCellModemusthavebeenEnabled,seetheCellmenuoftheMATLABeditor. Belowweseeanexample:
41
42
UsingCellsintheMATLABEditor TheCellsToolbarintheEditor:
WhyUseCells?
M-filesoftenhaveanaturalstructureconsistingofmultiplesections.Especiallyforlarger
files,youtypicallyfocuseffortsonasinglesectionatatime,workingwiththecodeinjust
thatsection.Similarly,whenconveyinginformationaboutyourM-filestoothers,oftenyou
describethesectionsofthecode.Tofacilitatetheseprocesses,useM-filecells,wherecell
meansasectionofcode.Specifically,MATLABusescellsforRapidcodeiterationinthe
Editor/Debugger—thismakestheexperimentalphaseofyourworkwithM-filescripts
easier. Task10:
UsingCells
Useoneofyourpreviousscriptsanddivideyourcodeintodifferentcells.Runthedifferent
Cellsindividually.
UsetheCellstoolstobrowsebetweenthedifferentCellsinyourscript.
[EndofTask]
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
7 ImportingData
ItisoftenneededtoimportdataintoMATLABforanalysisandcalculations,itcouldbedata
inaspreadsheetorloggeddatafromaDAQdevicethatyouwanttoanalyze.MATLABhave
powerfultoolsforbothimportingandexportingdata.
GivenanExcelfile:
ToopentheImportWizard,useFile→ImportData…:
OrinnewerversionsofMATLAB:
AFiledialogappears:
43
44
ImportingData Select,e.g.,aExcelSpreadsheetFile,andtheImportWizardappears:
ClickingFinishandthedatafromtheExcelfilewillbeavailableinMATLAB:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
45
ImportingData Beforeyoustart,youshouldwatchthevideo“ImportingDatafromFiles”.
Thevideoisavailablefrom:http://home.hit.no/~hansha/?training=matlab Task11:
ImportData
Createaspreadsheetfilewithsomedata(oruseanexistingspreadsheetwithdataifyou
have)andimportthedataintoMATLAB.
PlotthedatainMATLAB.
[EndofTask]
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
8 StructuresandCellArrays
Historically,thematrixwastheonlydatatypeinMATLAB.Vectorsandscalarsarespecial
casesofthegeneralmatrix.Nowsomenewandimportantdatastructureshavearrived.One
isthemulti-dimensionalarray,whichjustextendsthematrixtomorethantwodimensions.
Moreimportantarethestructureandthecellarray.
Inthischapterwewillusethesenewdatastructures.
Beforeyoustart,youshouldwatchthevideo“IntroducingStructuresandCellArrays”
Thevideoisavailablefrom:http://home.hit.no/~hansha/?training=matlab 8.1 Structures
Astructureisadatastructurethatcanholddiversedatatypes,notnecessarilynumbers,and
withnameddatacontainerscalledfields,similartoarecordwithfieldsinadatabase. Example:
>>tank.height = 0.4;
>>tank.diameter = 0.5;
>>tank.type = 'cylinder';
>>tank
tank = height: 0.4000
diameter: 0.5000
type: 'cylinder'
[EndofExample]
Task12:
UsingStructures
Createafunctionthatcalculatesthevolumeofdifferentobjects,suchasacylinder,a
sphere,etc.
UseStructurestosolvetheproblem.
[EndofTask]
46
9 AlternativestoMATLAB
HerearesomeotheralternativestoMATLABworthmention:
•
•
•
•
•
Octave
ScilabandScicos
LabVIEWMathScript
LabVIEW
Python
9.1 Octave
Octaveisafreesoftwaretoolfornumericalanalysisandvisualization.Thefunctionand
commandsyntaxisverysimilartoMATLAB.Manycontributedfunctionspackages(likethe
toolboxesinMATLAB)areavailable.Theycovercontroltheory,signalprocessing,simulation,
statisticsetc.TheyareinstalledautomaticallywhenyouinstallOctave.
ThereisnoSIMULINK-liketoolinOctave,buttherearemanysimulationfunctions(asin
ControlSystemToolboxinMATLAB). •
•
ReadmoreaboutOctaveontheirHomepage:http://www.gnu.org/software/octave/ ReadmoreaboutOctaveonWikipedia:http://en.wikipedia.org/wiki/GNU_Octave 9.2 ScilabandScicos
Scilabisafreescientificsoftwarepackagefornumericalcomputationsprovidingapowerful
opencomputingenvironmentforengineeringandscientificapplications.
Scilabisanopensourcesoftware.Since1994ithasbeendistributedfreelyalongwiththe
sourcecodeviatheInternet.Itiscurrentlyusedineducationalandindustrialenvironments
aroundtheworld.
ScilabisquitesimilartoMATLAB,andtherangeoffunctionsarecomparable.
OctaveismoresimilartoMATLABthantoScilab.OneproblemwithOctavehasbeenthat
dataplottingismorecumbersomeinOctavethaninScilab.
47
48
AlternativestoMATLAB OnenicethingaboutScilabisthatyougetScicosautomaticallyinstalledwhenyouinstall
Scilab.Scicosisablock-diagrambasedsimulationtoolsimilartoSimulinkandLabVIEW
SimulationModule.
•
•
•
•
ReadmoreaboutScilabontheirHomepage:http://www.scilab.org/
ReadmoreaboutScilabonWikipedia:http://en.wikipedia.org/wiki/Scilab
MasterScilabbyFinnHaugen:
http://home.hit.no/~finnh/scilab_scicos/scilab/index.htm
MasterScicosbyFinnHaugen:
http://home.hit.no/~finnh/scilab_scicos/scicos/index.htm
9.3 LabVIEWMathScript
MathScriptisahigh-level,text-basedprogramminglanguage.MathScriptincludesmore
than800built-infunctionsandthesyntaxissimilartoMATLAB.Youmayalsocreatecustommadem-filelikeyoudoinMATLAB.
MathScriptisanadd-onmoduletoLabVIEWbutyoudon’tneedtoknowLabVIEW
programminginordertouseMathScript.
FormoreinformationaboutMathScript,pleasereadtheTutorial“LabVIEWMathScript”.
MathScriptisanadd-onmoduletoLabVIEWbutyoudon’tneedtoknowLabVIEW
programminginordertouseMathScript.
FormoreinformationaboutMathScript,pleasereadtheTutorial“LabVIEWMathScript”.
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
49
9.3.1
AlternativestoMATLAB HowdoyoustartusingMathScript? YouneedtoinstallLabVIEWandtheLabVIEWMathScriptRTModule.Whennecessary
softwareisinstalled,startMathScriptbyopenLabVIEW:
IntheGettingStartedwindow,selectTools->MathScriptWindow...:
9.3.2
Functions
ThefigurebelowillustrateshowtocreateandusefunctionsinMathScript:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
50
AlternativestoMATLAB 9.3.3
ODESolversinMathScript
MathScriptoffersalsosomeODEsolvers,notasmanyasMATLABandothernames,butthe
principleisquitethesame.
BelowweseealistwithavailableODEsolvers:
Belowweseethedescriptionfortheode_rk23function:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
51
AlternativestoMATLAB 9.4 LabVIEW
LabVIEWisagraphicalprogramminglanguage,anditiswellsuitedforControland
Simulationapplications.
InthischapterwewilluseLabVIEWtocreateablockdiagrammodelandsimulateit,similar
towhatwehavedoneinSimulink.
9.4.1
TheLabVIEWEnvironment
LabVIEWprogramsarecalledVirtualInstruments,orVIs,becausetheirappearanceand
operationimitatephysicalinstruments,suchasoscilloscopesandmultimeters.LabVIEW
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
52
AlternativestoMATLAB containsacomprehensivesetoftoolsforacquiringanalyzing,displaying,andstoringdata,as
wellastoolstohelpyoutroubleshootyourcode.
WhenopeningLabVIEW,youfirstcometothe“GettingStarted”window.
InordertocreateanewVI,select“BlankVI”orinordertocreateanewLabVIEWproject,
select“Emptyproject”.
WhenyouopenablankVI,anuntitledfrontpanelwindowappears.Thiswindowdisplays
thefrontpanelandisoneofthetwoLabVIEWwindowsyouusetobuildaVI.Theother
windowcontainstheblockdiagram.Thesectionsbelowdescribethefrontpanelandthe
blockdiagram.
9.4.2
FrontPanel
WhenyouhavecreatedanewVIorselectedanexistingVI,theFrontPanelandtheBlock
DiagramforthatspecificVIwillappear.
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
53
AlternativestoMATLAB InLabVIEW,youbuildauserinterface,orfrontpanel,withcontrolsandindicators.Controls
areknobs,pushbuttons,dials,andotherinputdevices.Indicatorsaregraphs,LEDs,and
otherdisplays.
Youbuildthefrontpanelwithcontrolsandindicators,whicharetheinteractiveinputand
outputterminalsoftheVI,respectively.Controlsareknobs,pushbuttons,dials,andother
inputdevices.Indicatorsaregraphs,LEDs,andotherdisplays.Controlssimulateinstrument
inputdevicesandsupplydatatotheblockdiagramoftheVI.Indicatorssimulateinstrument
outputdevicesanddisplaydatatheblockdiagramacquiresorgenerates.
E.g.,a“Numeric”caneitherbea“NumericControl”ora“NumericIndicator”,asseenbelow.
Iyouselecta“NumericControl”,itcaneasybechangedtoan“NumericIndicator”byright
clickontheobjectanselect“ChangetoIndicator”
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
54
AlternativestoMATLAB Oropposite,Iyouselecta“NumericIndicator”,itcaneasybechangedtoan“Numeric
Control”byrightclickontheobjectanselect“ChangetoControl”
Thedifferencebetweena“NumericControl”anda“NumericIndicator”isthatfora
“NumericControl”youmayenteravalue,whilethe“NumericIndicator”isread-only,i.e.,
youmayonlyreadthevalue,notchangeit.
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
55
AlternativestoMATLAB Theappearanceisalsoslightlydifferent,the“NumericControl”hasanincrementandan
decrementbuttoninfront,whilethe“NumericIndicator”hasadarkerbackgroundcolorin
ordertoindicatethatitsread-only.
9.4.3
BlockDiagram
Afteryoubuildtheuserinterface,youaddcodeusingVIsandstructurestocontrolthefront
panelobjects.Theblockdiagramcontainsthiscode.Insomeways,theblockdiagram
resemblesaflowchart.
Afteryoubuildthefrontpanel,youaddcodeusinggraphicalrepresentationsoffunctionsto
controlthefrontpanelobjects.Theblockdiagramcontainsthisgraphicalsourcecode.Front
panelobjectsappearasterminals,ontheblockdiagram.Blockdiagramobjectsinclude
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
56
AlternativestoMATLAB terminals,subVIs,functions,constants,structures,andwires,whichtransferdataamong
otherblockdiagramobjects.
9.4.4 LabVIEWControlDesignandSimulation
Module
Inthischapterwewillfocusonhowtocreateandsimulateamodelusingthe“Simulation
Loop”andthecorrespondingblocksavailableinLabVIEW.
BelowweseetheSimulationpaletteinLabVIEWwith“SimulationLoop”andthe
correspondingblocksavailable:
Inthe“Simulation”Subpalettewehavethe“ControlandSimulationLoop”whichisvery
usefulinsimulations:
YoumustplaceallSimulationfunctionswithinaControl&SimulationLooporinasimulation
subsystem.YoualsocanplacesimulationsubsystemswithinaControl&SimulationLoopor
anothersimulationsubsystem,oryoucanplacesimulationsubsystemsonablockdiagram
outsideaControl&SimulationLooporrunthesimulationsubsystemsasstand-aloneVIs.
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
57
AlternativestoMATLAB TheControl&SimulationLoophasanInputNode(upperleftcorner)andanOutputNode
(upperrightcorner).UsetheInputNodetoconfiguresimulationparameters
programmatically.YoualsocanconfiguretheseparametersinteractivelyusingtheConfigure
SimulationParametersdialogbox.Accessthisdialogboxbydouble-clickingtheInputNode
orbyright-clickingtheborderandselectingConfigureSimulationParametersfromthe
shortcutmenu.
Inthe“ContinuousLinearSystems”Subpalettewehaveimportantblocksforwewilluse
whencreatingour model:
ThemostusedblocksprobablyareIntegrator,TransportDelay,State-SpaceandTransfer
Function.
Whenyouplacetheseblocksonthediagramyoumaydouble-clickorright-clickandthen
select“Configuration…” Integrator-Integratesacontinuousinputsignalusingtheordinarydifferential
equation(ODE)solveryouspecifyforthesimulation.
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
58
AlternativestoMATLAB TransportDelay-Delaystheinputsignalbytheamountoftimeyouspecify.
TransferFunction-Implementsasystemmodelintransferfunctionform.Youdefine
thesystemmodelbyspecifyingtheNumeratorandDenominatorofthetransferfunction
equation.
State-Space-Implementsasystemmodelinstate-spaceform.Youdefinethesystem
modelbyspecifyingtheinput,output,state,anddirecttransmissionmatrices.
The“SignalArithmetic”Subpaletteisalsousefulwhencreatingasimulationmodel:
Example:
BelowweseeanexampleofasimulationmodelusingtheControlandSimulationLoop.
Noticethefollowing:
Clickontheborderofthesimulationloopandselect“ConfigureSimulationParameters…”
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
59
AlternativestoMATLAB Thefollowingwindowappears(ConfigureSimulationParameters):
InthiswindowyousetsomeParametersregardingthesimulation,someimportantare:
•
•
FinalTime(s)–sethowlongthesimulationshouldlast.Foraninfinitetimeset“Inf”.
EnableSynchronizedTiming-Specifiesthatyouwanttosynchronizethetimingof
theControl&SimulationLooptoatimingsource.Toenablesynchronization,placea
checkmarkinthischeckboxandthenchooseatimingsourcefromtheSourcetype
listbox.
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
60
AlternativestoMATLAB ClicktheHelpbuttonformoredetails.
YoumayalsosetsomeoftheseParametersintheBlockDiagram:
YoumayusethemousetoincreasethenumbersofParametersandright-clickandselect
“SelectInput”.
[EndofExample]
9.5 MathematicsinLabVIEW
Whenitcomestomathematicsandnumericaltechniques,LabVIEWoffersfunctionality
similartowhatexistsinMATLAB.
BelowweseetheMathematicspaletteinLabVIEW:
Herewehavefunctionalityfor:
•
•
•
•
Basicmathoperations
LinearAlgebra
CurveFitting
Interpolation
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
61
•
•
•
•
•
•
•
AlternativestoMATLAB IntegrationandDifferentiation
Statistics
Optimization
DifferentialEquations(ODEs)
Polynomials
MATLABintegration(MATLABScript)
etc.
Belowwewilltakeacloserlookatsomeofthesefunctions.
9.5.1
BasicMath
LabVIEWhavelotsoffunctionalityforbasicmathoperations,trigonometricfunctions,etc.
NumericPaletteinLabVIEW:
BelowweseetheNumericpaletteinLabVIEW:
Herewehavebasicmathfunctions,suchasAdd,Subtract,Multiply,Divide,etc. Example:
Belowweseeasimpleexampleusingthebasicmathfeatures:
BlockDiagram:
FrontPanel:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
62
AlternativestoMATLAB [EndofExample]
9.5.2
LinearAlgebra
LABVIEWhavelotsofVIs(functions)forLinearAlgebra.BelowweseetheLinearAlgebra
paletteinLabVIEW:
LinearAlgebraPaletteinLabVIEW:
InLabVIEWisamatrixdefinedasa2dimensionalarray,whileavectorisdefinedasa1
dimensionalarray,seeFigurebelow:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
63
AlternativestoMATLAB 9.5.3
CurveFitting
LabVIEWofferslotsoffunctionalityforCurveFitting.
FittingpaletteinLabVIEW:
9.5.4
Interpolation
LabVIEWofferslotsoffunctionalityforInterpolation.
Interpolation&ExtrapolationpaletteinLabVIEW:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
64
AlternativestoMATLAB 9.5.5
IntegrationandDifferentiation
LabVIEWofferslotsoffunctionalityfornumericalintegrationanddifferentiation.
IntegrationandDifferentiationpaletteinLabVIEW:
9.5.6
Statistics
LabVIEWofferslotsoffunctionalityforStatistics,includingbasicfunctionalityforfinding
mean,median,standarddeviation,etc.
ProbabilityandStatisticspaletteinLabVIEW:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
65
AlternativestoMATLAB 9.5.7
Optimization
LabVIEWofferslotsoffunctionalityforOptimization.
OptimizationpaletteinLabVIEW:
9.5.8
DifferentialEquations(ODEs)
LabVIEWofferslotsoffunctionalityforsolvingDifferentialEquations.
OrdinaryDifferentialEquationspaletteinLabVIEW:
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
66
AlternativestoMATLAB 9.5.9
Polynomials
LabVIEWofferslotsoffunctionalityforcreatingandmanipulatingPolynomials.
PolynomialpaletteinLabVIEW:
9.6 MATLABIntegration(MATLABScript)in
LabVIEW
ItispossibletointegrateMathScriptcodeinLabVIEW,whichhassimilarsyntaxasMATLAB
(seepreviouschapteraboutMathScript).Inaddition,thereisalsopossibletointegrate
MATLABcodedirectlyusingsomethingcalledthe“MATLABScript”.
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
67
AlternativestoMATLAB The“MATLABScript”callstheMATLABsoftwaretoexecutescripts.Youmusthavealicensed
copyoftheMATLABsoftwareversion6.5orlaterinstalledonyourcomputertouseMATLAB
scriptnodesbecausethescriptnodesinvoketheMATLABsoftwarescriptservertoexecute
scriptswrittenintheMATLABlanguagesyntax.BecauseLabVIEWusesActiveXtechnologyto
implementMATLABscriptnodes,theyareavailableonlyonWindows.
Example:
BlockDiagram:
FrontPanel:
TheMATLABScriptNodeisfoundintheMathematicspalette(Mathematics→Scripts&
Formulas→ScriptNodes):
9.7 Python
Pythonisawidelyusedhigh-level,general-purpose,interpreted,dynamicprogramming
language.
YoucaninstallabasicPythonIDEfromwww.python.org. MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
68
AlternativestoMATLAB FormoreMATLABlookandfeeltheAnacondaPythondistributionisrecommended(withall
majorScientificpackagesincluded,suchasNumPy,SciPy,Matplotlib...). TheSpyderIDEisalsoincluded(whichhasmuchmorefeaturesthanthebasicIDE). DoyouwanttousePythoninVisualStudio?InstallPythonToolsforVisualStudio(Windows
only!).
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
AppendixA–MathScript
Functions
HerearesomedescriptionsforthemostusedMathScriptfunctionsusedinthiscourse.
Function
plot
tf
poles
tfinfo
step
lsim
Sys_order1
Sys_order2
damp
pid
conv
series
feedback
Description
Generatesaplot.plot(y)plotsthecolumnsofyagainstthe
indexesofthecolumns.
Createssystemmodelintransferfunctionform.Youalsocan
usethisfunctiontostate-spacemodelstotransferfunction
form.
Returnsthelocationsoftheclosed-looppolesofasystem
model.
Returnsinformationaboutatransferfunctionsystemmodel.
Createsastepresponseplotofthesystemmodel.Youalso
canusethisfunctiontoreturnthestepresponseofthe
modeloutputs.Ifthemodelisinstate-spaceform,youalso
canusethisfunctiontoreturnthestepresponseofthe
modelstates.Thisfunctionassumestheinitialmodelstates
arezero.Ifyoudonotspecifyanoutput,thisfunction
createsaplot.
Createsthelinearsimulationplotofasystemmodel.This
functioncalculatestheoutputofasystemmodelwhenaset
ofinputsexcitethemodel,usingdiscretesimulation.Ifyou
donotspecifyanoutput,thisfunctioncreatesaplot.
Constructsthecomponentsofafirst-ordersystemmodel
basedonagain,timeconstant,anddelaythatyouspecify.
Youcanusethisfunctiontocreateeitherastate-space
modeloratransferfunctionmodel,dependingontheoutput
parametersyouspecify.
Constructsthecomponentsofasecond-ordersystemmodel
basedonadampingratioandnaturalfrequencyyouspecify.
Youcanusethisfunctiontocreateeitherastate-space
modeloratransferfunctionmodel,dependingontheoutput
parametersyouspecify.
Returnsthedampingratiosandnaturalfrequenciesofthe
polesofasystemmodel.
Constructsaproportional-integral-derivative(PID)controller
modelineitherparallel,series,oracademicform.Referto
theLabVIEWControlDesignUserManualforinformation
aboutthesethreeforms. Computestheconvolutionoftwovectorsormatrices.
Connectstwosystemmodelsinseriestoproduceamodel
SysSerwithinputandoutputconnectionsyouspecify
Connectstwosystemmodelstogethertoproduceaclosedloopmodelusingnegativeorpositivefeedbackconnections
69
Example
>X = [0:0.01:1];
>Y = X.*X;
>plot(X, Y)
>num=[1];
>den=[1, 1, 1];
>H = tf(num, den)
>num=[1]
>den=[1,1]
>H=tf(num,den)
>poles(H)
>[num, den, delay, Ts] =
tfinfo(SysInTF)
>num=[1,1];
>den=[1,-1,3];
>H=tf(num,den);
>t=[0:0.01:10];
>step(H,t);
>t = [0:0.1:10]
>u = sin(0.1*pi*t)'
>lsim(SysIn, u, t)
>K = 1;
>tau = 1;
>H = sys_order1(K, tau)
>dr = 0.5
>wn = 20
>[num, den] = sys_order2(wn, dr)
>SysTF = tf(num, den)
>[A, B, C, D] = sys_order2(wn,
dr)
>SysSS = ss(A, B, C, D)
>[dr, wn, p] = damp(SysIn)
>Kc = 0.5;
>Ti = 0.25;
>SysOutTF = pid(Kc, Ti,
'academic');
>C1 = [1, 2, 3];
>C2 = [3, 4];
>C = conv(C1, C2)
>Hseries = series(H1,H2)
>SysClosed = feedback(SysIn_1,
SysIn_2)
70
ss
ssinfo
pade
bode
bodemag
margin
margins
AppendixA–MathScriptFunctions Constructsamodelinstate-spaceform.Youalsocanusethis
functiontoconverttransferfunctionmodelstostate-space
form.
Returnsinformationaboutastate-spacesystemmodel.
IncorporatestimedelaysintoasystemmodelusingthePade
approximationmethod,whichconvertsallresiduals.You
mustspecifythedelayusingthesetfunction.Youalsocan
usethisfunctiontocalculatecoefficientsofnumeratorand
denominatorpolynomialfunctionswithaspecifieddelay.
CreatestheBodemagnitudeandBodephaseplotsofa
systemmodel.Youalsocanusethisfunctiontoreturnthe
magnitudeandphasevaluesofamodelatfrequenciesyou
specify.Ifyoudonotspecifyanoutput,thisfunctioncreates
aplot.
CreatestheBodemagnitudeplotofasystemmodel.Ifyou
donotspecifyanoutput,thisfunctioncreatesaplot.
Calculatesand/orplotsthesmallestgainandphasemargins
ofasingle-inputsingle-output(SISO)systemmodel.Thegain
marginindicateswherethefrequencyresponsecrossesat0
decibels.Thephasemarginindicateswherethefrequency
responsecrosses-180degrees.Usethemarginsfunctionto
returnallgainandphasemarginsofaSISOmodel.
Calculatesallgainandphasemarginsofasingle-inputsingleoutput(SISO)systemmodel.Thegainmarginsindicate
wherethefrequencyresponsecrossesat0decibels.The
phasemarginsindicatewherethefrequencyresponse
crosses-180degrees.Usethemarginfunctiontoreturnonly
thesmallestgainandphasemarginsofaSISOmodel.
>A = eye(2)
>B = [0; 1]
>C = B'
>SysOutSS = ss(A, B, C)
>A = [1, 1; -1, 2]
>B = [1, 2]'
>C = [2, 1]
>D = 0
>SysInSS = ss(A, B, C, D)
>[A, B, C, D, Ts] =
ssinfo(SysInSS)
>[num, den] = pade(delay, order)
>[A, B, C, D] = pade(delay,
order)
>num=[4];
>den=[2, 1];
>H = tf(num, den)
>bode(H)
>[mag, wout] = bodemag(SysIn)
>[mag, wout] = bodemag(SysIn,
[wmin wmax])
>[mag, wout] = bodemag(SysIn,
wlist)
>num = [1]
>den = [1, 5, 6]
>H = tf(num, den)
margin(H)
>[gmf, gm, pmf, pm] = margins(H)
Formoredetailsaboutthesefunctions,type“helpcdt”togetanoverviewofallthe
functionsusedforControlDesignandSimulation.Fordetailedhelpaboutonespecific
function,type“help<function_name>”.
Plotsfunctions:Herearesomeusefulfunctionsforcreatingplots:plot,figure,subplot,grid,
axis,title,xlabel,ylabel,semilogx–formoreinformationabouttheplotsfunction,type
“helpplots”.
MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB
AppendixB:Mathematics
characters
71
Hans-PetterHalvorsen,M.Sc.
E-mail:[email protected]
Blog:http://home.hit.no/~hansha/
UniversityCollegeofSoutheastNorway
www.usn.no
Was this manual useful for you? yes no
Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Download PDF

advertisement