79
University College of Southeast Norway MATLAB Part III: Simulink and Advanced Topics Hans-Petter Halvorsen, 2016.10.04 http://home.hit.no/~hansha

MATLAB Course - Part III

  • Upload
    buinga

  • View
    255

  • Download
    6

Embed Size (px)

Citation preview

Page 1: MATLAB Course - Part III

UniversityCollegeofSoutheastNorway

MATLAB PartIII:SimulinkandAdvancedTopics

Hans-PetterHalvorsen,2016.10.04

http://home.hit.no/~hansha

Page 2: MATLAB Course - Part III

ii

PrefaceCopyrightYoucannotdistributeorcopythisdocumentwithoutpermissionfromtheauthor.Youcannotcopyorlinktothisdocumentdirectlyfromothersources,webpages,etc.Youshouldalwayslinktotheproperwebpagewherethisdocumentislocated,typicallyhttp://home.hit.no/~hansha/…

InthisMATLABCourseyouwilllearnbasicMATLABandhowtouseMATLABinControlandSimulationapplications.AnintroductiontoSimulinkandotherToolswillalsobegiven.

MATLABisatoolfortechnicalcomputing,computationandvisualizationinanintegratedenvironment.MATLABisanabbreviationforMATrixLABoratory,soitiswellsuitedformatrixmanipulationandproblemsolvingrelatedtoLinearAlgebra, Modelling,SimulationandControlapplications.

Thisisaself-pacedcoursebasedonthisdocumentandsomeshortvideosontheway.Thisdocumentcontainslotsofexamplesandself-pacedtasksthattheuserswillgothroughandsolveontheirown.Theusermaygothroughthetasksinthisdocumentintheirownpaceandtheinstructorwillbeavailableforguidancethroughoutthecourse.

TheMATLABCourseconsistsof3parts:

• MATLABCourse–PartI:IntroductiontoMATLAB• MATLABCourse–PartII:Modelling,SimulationandControl • MATLABCourse–PartIII:SimulinkandAdvancedTopics

InPartIIIofthecourse(PartIII:AdvancedTopics,SimulinkandotherTools)youwilllearnhowtousesomeofthemoreadvancedfeaturesinMATLAB.WewillalsotakeacloserlookatSimulink,whichisaBlockDiagramSimulationToolusedtogetherwithMATLAB.Wewillalsogiveanoverviewtoothertoolsfornumericalmathematicsandsimulation.

YoumustgothroughMATLABCourse–PartI:IntroductiontoMATLABbeforeyoustart.

ThecourseconsistsoflotsofTasksyoushouldsolvewhilereadingthiscoursemanualandwatchingthevideosreferredtointhetext.

Page 3: MATLAB Course - Part III

iii

Makesuretobringyourheadphonesforthevideosinthiscourse.Thecourseconsistsofseveralshortvideosthatwillgiveyouanintroductiontothedifferenttopicsinthecourse.

Prerequisites:Youshouldbefamiliarwithundergraduate-levelmathematicsandhaveexperiencewithbasiccomputeroperations.

WhatisMATLAB?

MATLABisatoolfortechnicalcomputing,computationandvisualizationinanintegratedenvironment.MATLABisanabbreviationforMATrixLABoratory,soitiswellsuitedformatrixmanipulationandproblemsolvingrelatedtoLinearAlgebra.

MATLABisdevelopedbyTheMathWorks.MATLABisashort-termforMATrixLABoratory.MATLABisinuseworld-widebyresearchersanduniversities.

Formoreinformation,seewww.mathworks.com

WhatisSimulink?

MATLABofferslotsofadditionalToolboxesfordifferentareassuchasControlDesign,ImageProcessing,DigitalSignalProcessing,etc.

Simulink,developedbyTheMathWorks,isacommercialtoolformodeling,simulatingandanalyzingdynamicsystems.Itsprimaryinterfaceisagraphicalblockdiagrammingtoolandacustomizablesetofblocklibraries.ItofferstightintegrationwiththerestoftheMATLABenvironmentandcaneitherdriveMATLABorbescriptedfromit.Simulinkiswidelyusedincontroltheoryanddigitalsignalprocessingforsimulationanddesign.

ThistrainingwillgiveyouthebasicknowledgeofSimulinkandhowyoucanuseittogetherwithMATLAB.

OnlineMATLABResources:MATLABBasics:

http://home.hit.no/~hansha/video/matlab_basics.php

Page 4: MATLAB Course - Part III

iv

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,downloadableMATLABcode,additionalresources,etc.

Page 5: MATLAB Course - Part III

v

TableofContentsPreface......................................................................................................................................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

Page 6: MATLAB Course - Part III

vi TableofContents

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

4.1 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: UsingCells................................................................................................42

7 ImportingData................................................................................................................43

Task11: ImportData.............................................................................................45

8 StructuresandCellArrays...............................................................................................46

8.1 Structures................................................................................................................46

Task12: UsingStructures......................................................................................46

9 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

Page 7: MATLAB Course - Part III

vii TableofContents

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

9.4.4 LabVIEWControlDesignandSimulationModule...........................................56

9.5 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

Page 8: MATLAB Course - Part III

1

1 IntroductionPart3:AdvancedTopics,SimulinkandotherToolsconsistsofthefollowingtopics:

• IntroductiontoSimulink• AdvancedTopicsinMATLAB:

o DebugginginMATLABo Moreaboutfunctionso MoreaboutPlotso UsingCellsintheMATLABEditoro ImportingDatao StructuresandCellArrays

• AlternativestoMATLAB

Page 9: MATLAB Course - Part III

2

2 SimulinkSimulinkisanenvironmentforsimulationandmodel-baseddesignfordynamicandembeddedsystems.Itprovidesaninteractivegraphicalenvironmentandacustomizablesetofblocklibrariesthatletyoudesign,simulate,implement,andtestavarietyoftime-varyingsystems,includingcommunications,controls,signalprocessing,videoprocessing,andimageprocessing.

Simulinkoffers:

• Aquickwayofdevelopyourmodelincontrasttotextbased-programminglanguagesuchase.g.,C.

• Simulinkhasintegratedsolvers.Intextbased-programminglanguagesuchase.g.,Cyouneedtowriteyourownsolver.

GraphicalProgramming:InSimulinkyouprograminagraphicalway.LabVIEWisanotherprogramminglanguagewhereyouusegraphicalprogramminginsteadoftext-basedprogramming.LabVIEWisdevelopedbyNationalInstruments.YouwilluseLabVIEWinalaterchapter

Beforeyoustart,youshouldwatchthefollowingvideos:

• “SimulinkOverview”• “GettingStartedwithSimulink”

Thevideosisavailablefrom:http://home.hit.no/~hansha/?training=matlab

2.1 StartusingSimulinkYoustartSimulinkfromtheMATLABIDE:

OpenMATLABandselecttheSimulinkiconintheToolbar:

Page 10: MATLAB Course - Part III

3 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

Ortype“simulink”intheCommandwindow,likethis:

Thenthefollowingwindowappears(SimulinkLibraryBrowser):

Page 11: MATLAB Course - Part III

4 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

TheSimulinkLibraryBrowseristhelibrarywhereyoufindalltheblocksyoumayuseinSimulink.Simulinksoftwareincludesanextensivelibraryoffunctionscommonlyusedinmodelingasystem.Theseinclude:

• Continuousanddiscretedynamicsblocks,suchasIntegration,Transferfunctions,TransportDelay,etc.

• Mathblocks,suchasSum,Product,Add,etc• Sources,suchasRamp,RandomGenerator,Step,etc

2.1.1 BlockLibraries

HerearesomecommonusedContinuousBlocks:

Page 12: MATLAB Course - Part III

5 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

HerearesomecommonusedMathOperationsBlocks:

HerearesomecommonusedSignalRoutingBlocks:

HerearesomecommonusedSinksBlocks:

HerearesomecommonusedSourcesBlocks:

Page 13: MATLAB Course - Part III

6 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

InadditiontherearelotsofblockindifferentToolboxes:

2.1.2 CreateanewModel

ClicktheNewiconontheToolbarinordertocreateanewSimulinkmodel:

Thefollowingwindowappears:

Page 14: MATLAB Course - Part III

7 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

YoumaynowdragtheblocksyouwanttousefromtheSimulinkLibraryBrowsertothemodelsurface(orright-clickonablockandselect“Addto…”).

Example:

Inthisexampleweplace(draganddrop)toblocks,aSineWaveandaScope,onthemodelsurface:

2.2 WiringtechniquesUsethemousetowiretheinputsandoutputsofthedifferentblocks.Inputsarelocatedontheleftsideoftheblocks,whileoutputsarelocatedontherightsideoftheblocks.

Page 15: MATLAB Course - Part III

8 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

Whenholdingthemouseoveraninputoranoutputthemousechangestothefollowingsymbol.

Usethemouse,whileholdingtheleftbuttondown,todragwiresfromtheinputtotheoutput.

AutomaticBlockConnection:

Anotherwiringtechniqueistoselectthesourceblock,thenholddowntheCtrlkeywhileleft-clickingonthedestinationblock.

Trythedifferenttechniquesontheexampleabove.

Connectionfromawiretoanotherblock

Ifwireaconnectionfromawiretoanotherblock,liketheexamplebelow,youneedtoholddowntheCtrlkeywhileleft-clickingonthewireandthentotheinputofthedesiredblock.

2.3 HelpWindowInordertoseedetailedinformationaboutthedifferentblocks,usethebuilt-inHelpsystem.

Page 16: MATLAB Course - Part III

9 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

AllstandardblocksinSimulinkhavedetailedHelp.ClicktheHelpbuttonintheBlockParameterwindowforthespecificblockinordertogetdetailedhelpforthatblock.

TheHelpWindowthenappearswithdetailedinformationabouttheselectedblock:

Page 17: MATLAB Course - Part III

10 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

2.4 ConfigurationTherearelotsofparametersyoumaywanttoconfigureregardingyoursimulation.Select“ConfigurationParameters…”intheSimulationmenu.

Thefollowingwindowappears:

Page 18: MATLAB Course - Part III

11 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

Hereyousetimportantparameterssuchas:

• StartandStoptimeforthesimulation• WhatkindofSolvertobeused(ode45,ode23etc.)• Fixed-step/Variable-step

Note!EachofthecontrolsontheConfigurationParametersdialogboxcorrespondstoaconfigurationparameterthatyoucansetviathe“sim”and“simset”commands.Youwilllearnmoreaboutthesecommandslater.

Solversarenumericalintegrationalgorithmsthatcomputethesystemdynamicsovertimeusinginformationcontainedinthemodel.Simulinkprovidessolverstosupportthesimulationofabroadrangeofsystems,includingcontinuous-time(analog),discrete-time(digital),hybrid(mixed-signal),andmultiratesystemsofanysize.

2.5 ExamplesBelowwewillgothroughsomeexamplesinordertoillustratehowtocreateblockdiagramsandrelatedfunctionality.

Example:

Integratorwithinitialvalue

Createthefollowingmodel(anintegrator)andrunthesimulation:

Page 19: MATLAB Course - Part III

12 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

Step1:Placetheblocksonthemodelsurface

Thisexampleusethefollowingblocks:

Step2:Configuration

Double-clickontheIntegratorblock.TheParameterwindowfortheIntegratorblockappears:

Page 20: MATLAB Course - Part III

13 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

Select“Initialconditionsource=external”.TheIntegratorblocknowlookslikethis:

Double-clickontheConstantblock.TheParameterwindowfortheConstantblockappears:

Page 21: MATLAB Course - Part III

14 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

IntheConstantvaluefieldwetypeintheinitialvaluefortheintegrator,e.g.,typethevalue1.

Step3:Wiring

Usethemousetowiretheinputsandoutputsofthedifferentblocks.

Whenholdingthemouseoveraninputoranoutputthemousechangetothefollowingsymbol.

DrawawirebetweentheoutputontheConstantblocktothelowerinputintheIntegratorblock,likethis:

Youcouldalsodolikethis:

Wiretherestoftheblockstogetherandyouwillgetthefollowingdiagram:

Page 22: MATLAB Course - Part III

15 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

Step4:Simulation

Startthesimulationbyclickingthe“StartSimulation”iconintheToolbar:

Step5:TheResults

Double-clickintheScopeblockinordertoseethesimulatedresult:

Example:

SineWave

Createtheblockdiagramasshownbelow:

Page 23: MATLAB Course - Part III

16 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

SetthefollowingparameterfortheIntegratorblock:

Theresultshouldbelikethis:

Page 24: MATLAB Course - Part III

17 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

Example:

Usingvectors

Createthefollowingblockdiagram:

FortheGainblock,typethefollowingparameters:

Page 25: MATLAB Course - Part III

18 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

Asyousee,wecanusestandardMATLABsyntaxtocreateavector.

Ifyouwanttoseethesignaldimensions,select“SignalDimensions”and“WideNonscalarLines”asshownhere:

Theblockdiagramshouldnowlooklikethis:

Page 26: MATLAB Course - Part III

19 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

Thethicklinesindicatevectors,whilethenumber(8)isthesizeofthevector.

Let’schangetheSaturationblock:

AsyouseeyoumayusestandardMATLABfunctionsandsyntax.

RunthesimulationandseetheresultsintheScopeblock.

Task1: SimulationinSimulink–BacteriaPopulation

Inthistaskwewillsimulateasimplemodelofabacteriapopulationinajar(knownfromaprevioustask).

Themodelisasfollows:

birthrate=bx

deathrate=px2

Page 27: MATLAB Course - Part III

20 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

Thenthetotalrateofchangeofbacteriapopulationis:

𝑥 = 𝑏𝑥 − 𝑝𝑥2

Setb=1/hourandp=0.5bacteria-hour

Wewillsimulatethenumberofbacteriainthejarafter1hour,assumingthatinitiallythereare100bacteriapresent.

Procedure:

1. Createtheblockdiagramforthesystemusing“pen&paper”2. StartSimulinkandcreateaNewModel3. DraginthenecessaryblocksfromtheSimulinkLibraryBrowser4. Configurethedifferentblocks(double-click/right-clickdependingonwhatyouneed).

Someblocksneedtobe“flipped”(Right-click→Format→FlipBlock),whileinotherblocksyouneedtosetavalue(double-click)

5. Drawlinesbetweenthedifferentblocksusingthemouse6. SetSimulationSettings(Simulation→ConfigurationParameters).Thesimulation

Time(StopTime)shouldbesetto1(hour)7. UseaScopetoseetheSimulatedResult

Youwillneedthefollowingblocks:

• Integratorblock Tosolvethedifferentialequation.Note!Initialvaluex0=100

• TwoGainblocks Forp(=0.5)andb(=1)

• Productblock Tocomputex2

• Sumblock Note!Oneplus(+)mustbechangedtominus(-)

• Scopeblock Toshowthesimulatedresult.Note!SettoAutoscale

[EndofTask]

2.6 Data-drivenModellingYoumayuseSimulinktogetherwithMATLABinordertospecifydataandparameterstoyourSimulinkmodel.YoumayspecifycommandsintheMATLABCommandWindoworascommandsinanm-file.Thisiscalleddata-drivenmodeling.

Page 28: MATLAB Course - Part III

21 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

2.6.1 UsingtheCommandwindow

Example:

Giventhefollowingsystem:

Note!Inordertoget3inputsontheScopeblock:

Double-clickontheScopeandselecttheParametersiconintheToolbar:

ThenselectNumberofAxes=3:

Configurethezero-orderholdblockslikethis:

Page 29: MATLAB Course - Part III

22 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

WritethefollowingintheCommandwindowinMATLAB:

RuntheSimulinkmodelfromtheSimulink:

Page 30: MATLAB Course - Part III

23 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

Wethengetthefollowingresults:

2.6.2 Usingam-file

ItisgoodpracticetobuildyourmodelinSimulinkandconfigureandrunthesimulationfromaMATLABm-file.

ATypicalm-filecouldlooklikethis:

Page 31: MATLAB Course - Part III

24 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

Youusethesimsetcommandtoconfigureyoursimulationparametersandthesimcommandtorunthesimulation.

Thevariablesyourefertointhem-fileissetintheConstantvaluefieldintheParameterwindowforeachblock.

2.6.3 SimulationCommands

Page 32: MATLAB Course - Part III

25 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

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-dampermodelinSimulinkandconfigureandrunthesimulationfromaMATLABm-file.

Inthisexerciseyouwillconstructasimulationdiagramthatrepresentsthebehaviorofadynamicsystem.Youwillsimulateaspring-massdampersystem.

𝐹(𝑡) − 𝑐𝑥(𝑡) − 𝑘𝑥(𝑡) = 𝑚𝑥(𝑡)

wheretisthesimulationtime,F(t)isanexternalforceappliedtothesystem,cisthedampingconstantofthespring,kisthestiffnessofthespring,misamass,andx(t)isthepositionofthemass. 𝑥 isthefirstderivativeoftheposition,whichequalsthevelocityofthemass. 𝑥 isthesecondderivativeoftheposition,whichequalstheaccelerationofthemass.

Thefollowingfigureshowsthisdynamicsystem.

Page 33: MATLAB Course - Part III

26 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

Thegoalistoviewthepositionx(t)ofthemassmwithrespecttotimet.Youcancalculatethepositionbyintegratingthevelocityofthemass.Youcancalculatethevelocitybyintegratingtheaccelerationofthemass.Ifyouknowtheforceandmass,youcancalculatethisaccelerationbyusingNewton'sSecondLawofMotion,givenbythefollowingequation:

Force=Mass×Acceleration

Therefore,

Acceleration=Force/Mass

Substitutingtermsfromthedifferentialequationaboveyieldsthefollowingequation:

𝑥 =1𝑚 (𝐹 − 𝑐𝑥 − 𝑘𝑥)

Youwillconstructasimulationdiagramthatiteratesthefollowingstepsoveraperiodoftime.

→Createtheblockdiagramforthemass-spring-dampermodelabove.

Insteadofhard-codingthemodelparametersintheblocksyoushouldrefertothemasvariablessetinanm-file.

Thesevariablesshouldbeconfigured:

• x_init• dxdt_init

Page 34: MATLAB Course - Part III

27 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

• 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-filewhereyouspecifymodelandsimulationparameters.Thenusethesimfunctioninordertorunthesimulationwithinthem-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.

Page 35: MATLAB Course - Part III

28 Simulink

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

SimulatethesysteminSimulinkwhereweplotthesolution 𝑥(𝑡) inthetimeinterval 0 ≤𝑡 ≤ 25

[EndofTask]

Page 36: MATLAB Course - Part III

29

3 DebugginginMATLABDebuggingisaboutdifferenttechniquesforfindingbugs(errorsthatmakeyourcodenotworkasexpected)inyourcode.

Inallbutthesimplestprograms,youarelikelytoencountersometypeofunexpectedbehaviorwhenyouruntheprogramforthefirsttime.Programdefectscanshowupintheformofwarningorerrormessagesdisplayedinthecommandwindow,programsthathang(neverterminate),inaccurateresults,orsomenumberofothersymptoms.

Itisdifficulttowritecodewithouterrors(bugs),butMATLABhavepowerfulDebuggingfunctionality,similartoothertoolslike,e.g.,VisualStudio.

Whywecallitdebugging?Theyfoundabug(actuallyamoth)insideacomputerin1947thatmadetheprogramnotbehavingasexpected.Thiswasthe“first”realbugwhichwasdebugged.

Step1:RemovingWarningsandErrorsnotifiedbyMATLAB

ThefirststepinordertoavoiderrorsistoremoveallwarningsanderrorsnotifiesbyMATLABintheEditor.OntherightsideoftheEditortherewillbeshownsymbolstoillustratethatMATLABhavefoundpotentialerrorsinyourcode.

Warnings-Clickthe symbolstogetmoreinformationaboutaspecificwarning

Example:

Page 37: MATLAB Course - Part III

30 DebugginginMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

Errors-Clickthe symbolstogetmoreinformationaboutaspecificerror

Example:

→TakenecessaryactionsinordertoremovetheseErrorsandWarnings!

Step2:UsingDebuggingToolsandTechniquesintheMATLABEditor

InadditionMATLABhavemoresophisticateddebuggingtoolswewilllearnmoreaboutbelow.Thesearetoolsyouusewhenyourprogramisrunning.

BelowweseethebasicdebuggingfunctionalityinMATLAB:

Page 38: MATLAB Course - Part III

31 DebugginginMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

TheMATLABDebuggerenablesyoutoexaminetheinnerworkingsofyourprogramwhileyourunit.Youcanstoptheexecutionofyourprogramatanypointandthencontinuefromthatpoint,steppingthroughthecodelinebylineandexaminingtheresultsofeachoperationperformed.YouhavethechoiceofoperatingthedebuggerfromtheEditorwindowthatdisplaysyourprogram,fromtheMATLABcommandline,orboth.

3.1 TheDebuggingProcessYoucanstepthroughtheprogramrightfromthestartifyouwant.Forlongerprograms,youwillprobablysavetimebystoppingtheprogramsomewhereinthemiddleandsteppingthroughfromthere.Youcandothisbyapproximatingwheretheprogramcodebreaksandsettingastoppingpoint(orbreakpoint)atthatline.Onceabreakpointhasbeenset,startyourprogram.TheMATLABEditor/Debuggerwindowwillshowagreenarrowpointingtothenextlinetoexecute.Fromthispoint,youcanexamineanyvaluespassedintotheprogram,ortheresultsofeachoperationperformed.Youcanstepthroughtheprogramlinebylinetoseewhichpathistakenandwhy.Youcanstepintoanyfunctionsthatyourprogramcalls,orchoosetostepoverthemandjustseetheendresults.Youcanalsomodifythevaluesassignedtoavariableandseehowthataffectstheoutcome.

Whentheprogramisindebug-mode,thecommandpromptischangedto“K>>”andthefollowingmessageappearsinthestatusbar:

Yourcodecouldlooksomethinglikethis:

Page 39: MATLAB Course - Part III

32 DebugginginMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

Aredcircleindicatesthatyouhavesetabreakpoint,whichmeansyourprogramwillstopatthisplaceinyourcodeandwaitforfurtherinstructionsfromyou.

Thegreenarrowindicatesatwhatlineyourprogramisatthemoment.

Nowyoucanusethe“debuggingtoolbar”tostepthroughyourcode:

The“debuggingtoolbar”containsthefollowingbuttons:

Set/ClearBreakpoint

ClearallBreakpoints

Stepthroughtheprogram,linebyline

Stepin(toafunction,etc.)

Stepout(ofafunction,etc.)

Continue

ExitDebugmode

Task4: Debugging

Createasimilarprogramlikethis:

Page 40: MATLAB Course - Part III

33 DebugginginMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

SetaBreakpointinsidetheloopandusetheDebuggingfunctionalitytostepthroughtheprogramandwatchtheresultineachiteration.

Testallthedifferentbuttonsinthe“debuggingtoolbar”:

Inadditionyoushouldopensomeofyourpreviousprogramsyouhavemade,andtrythedebuggingtoolsonthem.

[EndofTask]

Page 41: MATLAB Course - Part III

34

4 MoreaboutFunctions

4.1 GettingtheInputandOutputArguments

Afunctionmayhaveseveralinputsandseveraloutputs.Usenarginandnargouttodeterminethenumberofinputandoutputargumentsinaparticularfunctioncall.Usenargchkandnargoutchktoverifythatyourfunctioniscalledwiththerequirednumberofinputandoutputarguments.

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 =

Page 42: MATLAB Course - Part III

35 MoreaboutFunctions

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

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,theerrorfunctionisrecommendedinsteadofthedispfunction,butbothshouldwork.

[EndofExample]

Task5: CreateaFunction

You’vehaveprobablyexperiencedstandingontopofahillormountainandfeelinglikeyoucanseeforever.Howfarcanyoureallysee?Itdependsontheheightofthemountainandtheradiusoftheearth,asshowninthesketchbelow.

Inthistaskwewillcreateafunctionthatfindsthedistancetothehorizon𝑥F.

YoumayusethePythagoreanlawtofind 𝑥F:

Page 43: MATLAB Course - Part III

36 MoreaboutFunctions

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

𝑅2 = 𝑥F2 = (𝑅 + ℎ)2 ⇔ 𝑥F = ℎ 2𝑅 + ℎ

𝐷 isthediameteroftheearth, 𝑅 istheradiusoftheearth, ℎ isyourheightabovetheearthstandingonamountain.Theradiusontheearthis 𝑅 = 6378𝑘𝑚.

→Createafunctionthatfindsxhfrominputparameterh,

>>xh=horizon(h)

HowfarcanyouseeifyouareontopoftheMountEverest?

Makesurethefunctionmayhandlevectorinputsandcreateahelptextforthefunctionthatdescribeswhatthefunctionisdoing.

→Createascriptwhereyouusethefunctiontoplothvs.xhwherehisavectorfrom1to8000meters.Createlabels,titleandalegendintheplot.

[EndofTask]

Task6: OptionalInputs:Usingnarginandnargchk

Thedistancetothehorizonisquitedifferentonthemoonthanontheearthbecausetheradiusisdifferentforeach.

→ExtendyourfunctionsothatRcouldbeanoptionalinputtothefunction,e.g.:

>>xh=horizon(h,R)

Ifxh=horizon(h)isused,RisassumedtobeR=6378km(theearth).

→Usenargintosolvetheproblem.Usealsonargchktovalidatethenumberofinputs.

HowfarcouldyouseeifthemoonhadamountainsimilartoMountEverest?Theradiusonthemoonis 𝑅 = 1737𝑘𝑚.

[EndofTask]

Task7: OptionalOutputs:Usingnargoutandnargoutchk

Letsaywealsomaywanttofindtheangle(a)betweenradiustothehorizonandtheobserver(youstandingontopofthemountain).Seetheillustrationabove.

→Extendyourfunctionsothattheangle 𝒂 couldbeanoptionaloutputfromthefunction,e.g.:

>>[xh,a]=horizon(h,R)

Page 44: MATLAB Course - Part III

37 MoreaboutFunctions

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

Ifxh=horizon(h,R)isused,ashouldbeignored(onlyxhiscalculated).

→Usenargouttosolvetheproblem.Usealsonargoutchktovalidatethenumberofoutputs.

Theangle 𝑎 isgivenby:

tan 𝑎 =𝑥F𝑅 ⇔ 𝑎 = atan

𝑥F𝑅

Note!Youhavetoconvertfromradianstodegrees(2𝜋 = 360S).Useyourfunctionr2dwhichyoucreatedinaprevioustask.

[EndofTask]

Page 45: MATLAB Course - Part III

38

5 MoreaboutPlotsMATLABhaveadvancePlotfunctionality.WehavealreadyusedtheplotfunctionalityinMATLABinadozensofexamples.InthischapterwewilllearnmoreabouttheadvancedplottingfunctionalitythatMATLABoffers.

5.1 LaTEXorTEXCommandsWhenusinglabels,legendsandtitlesinaplotyousometimeswantusemoreadvancedlabels,titles,legendsuchas:

“Solutionof sin 𝑥 𝑑𝑥V< ”

ThisisdonebyusingLaTeXorTeXcommands.

InLaTeXtypesetting,mathematicalexpressionsarebracketedbythe$$symbol.Using$bracketing,indicatesin-linemath.

Example:

TheMATLABcode:

legend({'$$\frac{-b \pm \sqrt{b^{2}-4ac}}{2a}$$'}, 'Interpreter', 'LaTeX') title({'Equation: $\frac{-b \pm \sqrt{b^{2}-4ac}}{2a}$'}, 'Interpreter', 'LaTeX')

givesthefollowingplot:

Page 46: MATLAB Course - Part III

39 MoreaboutPlots

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

[EndofExample]

SeeAppendixB:Mathematicscharacters.

Task8: LATEXCommands

UseMATLABtocreatethefollowingplot:

[EndofTask]

Task9: 3DPlot

Useyourxh=horizon(h,R) fromaprevioustasktocreateameshplotwhereyouplotxhfordifferentvaluesofhandRrespectively.

Tip!CallthefunctioninnestedForLoopsfordifferentvaluesforhandRrespectively.

Page 47: MATLAB Course - Part III

40 MoreaboutPlots

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

[EndofTask]

Page 48: MATLAB Course - Part III

41

6 UsingCellsintheMATLABEditor

YoumaystructureMATLABcodeintheeditorbydefiningtextcells.Essentially,atextcellisinitiatedbyputtingthesymbol%%(double%character)inthefirstpositionofaline.Thecellendsonthelineprecedingthenext%%symbol.Afterthe%%symbol,aspaceshouldbeinserted,followedbyadescriptivetext.TheMATLABEditormarksacellbyframingitwithayellowbox:whenyouputthecursorinacell,theframeisshown.Inorderforthistowork,theCellModemusthavebeenEnabled,seetheCellmenuoftheMATLABeditor.

Belowweseeanexample:

Page 49: MATLAB Course - Part III

42 UsingCellsintheMATLABEditor

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

TheCellsToolbarintheEditor:

WhyUseCells?

M-filesoftenhaveanaturalstructureconsistingofmultiplesections.Especiallyforlargerfiles,youtypicallyfocuseffortsonasinglesectionatatime,workingwiththecodeinjustthatsection.Similarly,whenconveyinginformationaboutyourM-filestoothers,oftenyoudescribethesectionsofthecode.Tofacilitatetheseprocesses,useM-filecells,wherecellmeansasectionofcode.Specifically,MATLABusescellsforRapidcodeiterationintheEditor/Debugger—thismakestheexperimentalphaseofyourworkwithM-filescriptseasier.

Task10: UsingCells

Useoneofyourpreviousscriptsanddivideyourcodeintodifferentcells.RunthedifferentCellsindividually.

UsetheCellstoolstobrowsebetweenthedifferentCellsinyourscript.

[EndofTask]

Page 50: MATLAB Course - Part III

43

7 ImportingDataItisoftenneededtoimportdataintoMATLABforanalysisandcalculations,itcouldbedatainaspreadsheetorloggeddatafromaDAQdevicethatyouwanttoanalyze.MATLABhavepowerfultoolsforbothimportingandexportingdata.

GivenanExcelfile:

ToopentheImportWizard,useFile→ImportData…:

OrinnewerversionsofMATLAB:

AFiledialogappears:

Page 51: MATLAB Course - Part III

44 ImportingData

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

Select,e.g.,aExcelSpreadsheetFile,andtheImportWizardappears:

ClickingFinishandthedatafromtheExcelfilewillbeavailableinMATLAB:

Page 52: MATLAB Course - Part III

45 ImportingData

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

Beforeyoustart,youshouldwatchthevideo“ImportingDatafromFiles”.

Thevideoisavailablefrom:http://home.hit.no/~hansha/?training=matlab

Task11: ImportData

Createaspreadsheetfilewithsomedata(oruseanexistingspreadsheetwithdataifyouhave)andimportthedataintoMATLAB.

PlotthedatainMATLAB.

[EndofTask]

Page 53: MATLAB Course - Part III

46

8 StructuresandCellArraysHistorically,thematrixwastheonlydatatypeinMATLAB.Vectorsandscalarsarespecialcasesofthegeneralmatrix.Nowsomenewandimportantdatastructureshavearrived.Oneisthemulti-dimensionalarray,whichjustextendsthematrixtomorethantwodimensions.Moreimportantarethestructureandthecellarray.

Inthischapterwewillusethesenewdatastructures.

Beforeyoustart,youshouldwatchthevideo“IntroducingStructuresandCellArrays”

Thevideoisavailablefrom:http://home.hit.no/~hansha/?training=matlab

8.1 StructuresAstructureisadatastructurethatcanholddiversedatatypes,notnecessarilynumbers,andwithnameddatacontainerscalledfields,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,asphere,etc.

UseStructurestosolvetheproblem.

[EndofTask]

Page 54: MATLAB Course - Part III

47

9 AlternativestoMATLABHerearesomeotheralternativestoMATLABworthmention:

• Octave• ScilabandScicos• LabVIEWMathScript• LabVIEW• Python

9.1 OctaveOctaveisafreesoftwaretoolfornumericalanalysisandvisualization.ThefunctionandcommandsyntaxisverysimilartoMATLAB.Manycontributedfunctionspackages(likethetoolboxesinMATLAB)areavailable.Theycovercontroltheory,signalprocessing,simulation,statisticsetc.TheyareinstalledautomaticallywhenyouinstallOctave.

ThereisnoSIMULINK-liketoolinOctave,buttherearemanysimulationfunctions(asinControlSystemToolboxinMATLAB).

• ReadmoreaboutOctaveontheirHomepage:http://www.gnu.org/software/octave/ • ReadmoreaboutOctaveonWikipedia:http://en.wikipedia.org/wiki/GNU_Octave

9.2 ScilabandScicosScilabisafreescientificsoftwarepackagefornumericalcomputationsprovidingapowerfulopencomputingenvironmentforengineeringandscientificapplications.

Scilabisanopensourcesoftware.Since1994ithasbeendistributedfreelyalongwiththesourcecodeviatheInternet.Itiscurrentlyusedineducationalandindustrialenvironmentsaroundtheworld.

ScilabisquitesimilartoMATLAB,andtherangeoffunctionsarecomparable.

OctaveismoresimilartoMATLABthantoScilab.OneproblemwithOctavehasbeenthatdataplottingismorecumbersomeinOctavethaninScilab.

Page 55: MATLAB Course - Part III

48 AlternativestoMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

OnenicethingaboutScilabisthatyougetScicosautomaticallyinstalledwhenyouinstallScilab.Scicosisablock-diagrambasedsimulationtoolsimilartoSimulinkandLabVIEWSimulationModule.

• 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 LabVIEWMathScriptMathScriptisahigh-level,text-basedprogramminglanguage.MathScriptincludesmorethan800built-infunctionsandthesyntaxissimilartoMATLAB.Youmayalsocreatecustom-madem-filelikeyoudoinMATLAB.

MathScriptisanadd-onmoduletoLabVIEWbutyoudon’tneedtoknowLabVIEWprogramminginordertouseMathScript.

FormoreinformationaboutMathScript,pleasereadtheTutorial“LabVIEWMathScript”.

MathScriptisanadd-onmoduletoLabVIEWbutyoudon’tneedtoknowLabVIEWprogramminginordertouseMathScript.

FormoreinformationaboutMathScript,pleasereadtheTutorial“LabVIEWMathScript”.

Page 56: MATLAB Course - Part III

49 AlternativestoMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

9.3.1 HowdoyoustartusingMathScript?

YouneedtoinstallLabVIEWandtheLabVIEWMathScriptRTModule.Whennecessarysoftwareisinstalled,startMathScriptbyopenLabVIEW:

IntheGettingStartedwindow,selectTools->MathScriptWindow...:

9.3.2 Functions

ThefigurebelowillustrateshowtocreateandusefunctionsinMathScript:

Page 57: MATLAB Course - Part III

50 AlternativestoMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

9.3.3 ODESolversinMathScript

MathScriptoffersalsosomeODEsolvers,notasmanyasMATLABandothernames,buttheprincipleisquitethesame.

BelowweseealistwithavailableODEsolvers:

Belowweseethedescriptionfortheode_rk23function:

Page 58: MATLAB Course - Part III

51 AlternativestoMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

9.4 LabVIEWLabVIEWisagraphicalprogramminglanguage,anditiswellsuitedforControlandSimulationapplications.

InthischapterwewilluseLabVIEWtocreateablockdiagrammodelandsimulateit,similartowhatwehavedoneinSimulink.

9.4.1 TheLabVIEWEnvironment

LabVIEWprogramsarecalledVirtualInstruments,orVIs,becausetheirappearanceandoperationimitatephysicalinstruments,suchasoscilloscopesandmultimeters.LabVIEW

Page 59: MATLAB Course - Part III

52 AlternativestoMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

containsacomprehensivesetoftoolsforacquiringanalyzing,displaying,andstoringdata,aswellastoolstohelpyoutroubleshootyourcode.

WhenopeningLabVIEW,youfirstcometothe“GettingStarted”window.

InordertocreateanewVI,select“BlankVI”orinordertocreateanewLabVIEWproject,select“Emptyproject”.

WhenyouopenablankVI,anuntitledfrontpanelwindowappears.ThiswindowdisplaysthefrontpanelandisoneofthetwoLabVIEWwindowsyouusetobuildaVI.Theotherwindowcontainstheblockdiagram.Thesectionsbelowdescribethefrontpanelandtheblockdiagram.

9.4.2 FrontPanel

WhenyouhavecreatedanewVIorselectedanexistingVI,theFrontPanelandtheBlockDiagramforthatspecificVIwillappear.

Page 60: MATLAB Course - Part III

53 AlternativestoMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

InLabVIEW,youbuildauserinterface,orfrontpanel,withcontrolsandindicators.Controlsareknobs,pushbuttons,dials,andotherinputdevices.Indicatorsaregraphs,LEDs,andotherdisplays.

Youbuildthefrontpanelwithcontrolsandindicators,whicharetheinteractiveinputandoutputterminalsoftheVI,respectively.Controlsareknobs,pushbuttons,dials,andotherinputdevices.Indicatorsaregraphs,LEDs,andotherdisplays.ControlssimulateinstrumentinputdevicesandsupplydatatotheblockdiagramoftheVI.Indicatorssimulateinstrumentoutputdevicesanddisplaydatatheblockdiagramacquiresorgenerates.

E.g.,a“Numeric”caneitherbea“NumericControl”ora“NumericIndicator”,asseenbelow.

Iyouselecta“NumericControl”,itcaneasybechangedtoan“NumericIndicator”byrightclickontheobjectanselect“ChangetoIndicator”

Page 61: MATLAB Course - Part III

54 AlternativestoMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

Oropposite,Iyouselecta“NumericIndicator”,itcaneasybechangedtoan“NumericControl”byrightclickontheobjectanselect“ChangetoControl”

Thedifferencebetweena“NumericControl”anda“NumericIndicator”isthatfora“NumericControl”youmayenteravalue,whilethe“NumericIndicator”isread-only,i.e.,youmayonlyreadthevalue,notchangeit.

Page 62: MATLAB Course - Part III

55 AlternativestoMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

Theappearanceisalsoslightlydifferent,the“NumericControl”hasanincrementandandecrementbuttoninfront,whilethe“NumericIndicator”hasadarkerbackgroundcolorinordertoindicatethatitsread-only.

9.4.3 BlockDiagram

Afteryoubuildtheuserinterface,youaddcodeusingVIsandstructurestocontrolthefrontpanelobjects.Theblockdiagramcontainsthiscode.Insomeways,theblockdiagramresemblesaflowchart.

Afteryoubuildthefrontpanel,youaddcodeusinggraphicalrepresentationsoffunctionstocontrolthefrontpanelobjects.Theblockdiagramcontainsthisgraphicalsourcecode.Frontpanelobjectsappearasterminals,ontheblockdiagram.Blockdiagramobjectsinclude

Page 63: MATLAB Course - Part III

56 AlternativestoMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

terminals,subVIs,functions,constants,structures,andwires,whichtransferdataamongotherblockdiagramobjects.

9.4.4 LabVIEWControlDesignandSimulationModule

Inthischapterwewillfocusonhowtocreateandsimulateamodelusingthe“SimulationLoop”andthecorrespondingblocksavailableinLabVIEW.

BelowweseetheSimulationpaletteinLabVIEWwith“SimulationLoop”andthecorrespondingblocksavailable:

Inthe“Simulation”Subpalettewehavethe“ControlandSimulationLoop”whichisveryusefulinsimulations:

YoumustplaceallSimulationfunctionswithinaControl&SimulationLooporinasimulationsubsystem.YoualsocanplacesimulationsubsystemswithinaControl&SimulationLooporanothersimulationsubsystem,oryoucanplacesimulationsubsystemsonablockdiagramoutsideaControl&SimulationLooporrunthesimulationsubsystemsasstand-aloneVIs.

Page 64: MATLAB Course - Part III

57 AlternativestoMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

TheControl&SimulationLoophasanInputNode(upperleftcorner)andanOutputNode(upperrightcorner).UsetheInputNodetoconfiguresimulationparametersprogrammatically.YoualsocanconfiguretheseparametersinteractivelyusingtheConfigureSimulationParametersdialogbox.Accessthisdialogboxbydouble-clickingtheInputNodeorbyright-clickingtheborderandselectingConfigureSimulationParametersfromtheshortcutmenu.

Inthe“ContinuousLinearSystems”Subpalettewehaveimportantblocksforwewillusewhencreatingour model:

ThemostusedblocksprobablyareIntegrator,TransportDelay,State-SpaceandTransferFunction.

Whenyouplacetheseblocksonthediagramyoumaydouble-clickorright-clickandthenselect“Configuration…”

Integrator-Integratesacontinuousinputsignalusingtheordinarydifferentialequation(ODE)solveryouspecifyforthesimulation.

Page 65: MATLAB Course - Part III

58 AlternativestoMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

TransportDelay-Delaystheinputsignalbytheamountoftimeyouspecify.

TransferFunction-Implementsasystemmodelintransferfunctionform.YoudefinethesystemmodelbyspecifyingtheNumeratorandDenominatorofthetransferfunctionequation.

State-Space-Implementsasystemmodelinstate-spaceform.Youdefinethesystemmodelbyspecifyingtheinput,output,state,anddirecttransmissionmatrices.

The“SignalArithmetic”Subpaletteisalsousefulwhencreatingasimulationmodel:

Example:

BelowweseeanexampleofasimulationmodelusingtheControlandSimulationLoop.

Noticethefollowing:

Clickontheborderofthesimulationloopandselect“ConfigureSimulationParameters…”

Page 66: MATLAB Course - Part III

59 AlternativestoMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

Thefollowingwindowappears(ConfigureSimulationParameters):

InthiswindowyousetsomeParametersregardingthesimulation,someimportantare:

• FinalTime(s)–sethowlongthesimulationshouldlast.Foraninfinitetimeset“Inf”.• EnableSynchronizedTiming-Specifiesthatyouwanttosynchronizethetimingof

theControl&SimulationLooptoatimingsource.Toenablesynchronization,placeacheckmarkinthischeckboxandthenchooseatimingsourcefromtheSourcetypelistbox.

Page 67: MATLAB Course - Part III

60 AlternativestoMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

ClicktheHelpbuttonformoredetails.

YoumayalsosetsomeoftheseParametersintheBlockDiagram:

YoumayusethemousetoincreasethenumbersofParametersandright-clickandselect“SelectInput”.

[EndofExample]

9.5 MathematicsinLabVIEWWhenitcomestomathematicsandnumericaltechniques,LabVIEWoffersfunctionalitysimilartowhatexistsinMATLAB.

BelowweseetheMathematicspaletteinLabVIEW:

Herewehavefunctionalityfor:

• Basicmathoperations• LinearAlgebra• CurveFitting• Interpolation

Page 68: MATLAB Course - Part III

61 AlternativestoMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

• 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:

Page 69: MATLAB Course - Part III

62 AlternativestoMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

[EndofExample]

9.5.2 LinearAlgebra

LABVIEWhavelotsofVIs(functions)forLinearAlgebra.BelowweseetheLinearAlgebrapaletteinLabVIEW:

LinearAlgebraPaletteinLabVIEW:

InLabVIEWisamatrixdefinedasa2dimensionalarray,whileavectorisdefinedasa1dimensionalarray,seeFigurebelow:

Page 70: MATLAB Course - Part III

63 AlternativestoMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

9.5.3 CurveFitting

LabVIEWofferslotsoffunctionalityforCurveFitting.

FittingpaletteinLabVIEW:

9.5.4 Interpolation

LabVIEWofferslotsoffunctionalityforInterpolation.

Interpolation&ExtrapolationpaletteinLabVIEW:

Page 71: MATLAB Course - Part III

64 AlternativestoMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

9.5.5 IntegrationandDifferentiation

LabVIEWofferslotsoffunctionalityfornumericalintegrationanddifferentiation.

IntegrationandDifferentiationpaletteinLabVIEW:

9.5.6 Statistics

LabVIEWofferslotsoffunctionalityforStatistics,includingbasicfunctionalityforfindingmean,median,standarddeviation,etc.

ProbabilityandStatisticspaletteinLabVIEW:

Page 72: MATLAB Course - Part III

65 AlternativestoMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

9.5.7 Optimization

LabVIEWofferslotsoffunctionalityforOptimization.

OptimizationpaletteinLabVIEW:

9.5.8 DifferentialEquations(ODEs)

LabVIEWofferslotsoffunctionalityforsolvingDifferentialEquations.

OrdinaryDifferentialEquationspaletteinLabVIEW:

Page 73: MATLAB Course - Part III

66 AlternativestoMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

9.5.9 Polynomials

LabVIEWofferslotsoffunctionalityforcreatingandmanipulatingPolynomials.

PolynomialpaletteinLabVIEW:

9.6 MATLABIntegration(MATLABScript)inLabVIEW

ItispossibletointegrateMathScriptcodeinLabVIEW,whichhassimilarsyntaxasMATLAB(seepreviouschapteraboutMathScript).Inaddition,thereisalsopossibletointegrateMATLABcodedirectlyusingsomethingcalledthe“MATLABScript”.

Page 74: MATLAB Course - Part III

67 AlternativestoMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

The“MATLABScript”callstheMATLABsoftwaretoexecutescripts.YoumusthavealicensedcopyoftheMATLABsoftwareversion6.5orlaterinstalledonyourcomputertouseMATLABscriptnodesbecausethescriptnodesinvoketheMATLABsoftwarescriptservertoexecutescriptswrittenintheMATLABlanguagesyntax.BecauseLabVIEWusesActiveXtechnologytoimplementMATLABscriptnodes,theyareavailableonlyonWindows.

Example:

BlockDiagram: FrontPanel:

TheMATLABScriptNodeisfoundintheMathematicspalette(Mathematics→Scripts&Formulas→ScriptNodes):

9.7 PythonPythonisawidelyusedhigh-level,general-purpose,interpreted,dynamicprogramminglanguage.

YoucaninstallabasicPythonIDEfromwww.python.org.

Page 75: MATLAB Course - Part III

68 AlternativestoMATLAB

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

FormoreMATLABlookandfeeltheAnacondaPythondistributionisrecommended(withallmajorScientificpackagesincluded,suchasNumPy,SciPy,Matplotlib...).

TheSpyderIDEisalsoincluded(whichhasmuchmorefeaturesthanthebasicIDE).

DoyouwanttousePythoninVisualStudio?InstallPythonToolsforVisualStudio(Windowsonly!).

Page 76: MATLAB Course - Part III

69

AppendixA–MathScriptFunctionsHerearesomedescriptionsforthemostusedMathScriptfunctionsusedinthiscourse.

Function Description Exampleplot Generatesaplot.plot(y)plotsthecolumnsofyagainstthe

indexesofthecolumns.>X = [0:0.01:1]; >Y = X.*X; >plot(X, Y)

tf Createssystemmodelintransferfunctionform.Youalsocanusethisfunctiontostate-spacemodelstotransferfunctionform.

>num=[1]; >den=[1, 1, 1]; >H = tf(num, den)

poles Returnsthelocationsoftheclosed-looppolesofasystemmodel.

>num=[1] >den=[1,1] >H=tf(num,den) >poles(H)

tfinfo Returnsinformationaboutatransferfunctionsystemmodel. >[num, den, delay, Ts] = tfinfo(SysInTF)

step Createsastepresponseplotofthesystemmodel.Youalsocanusethisfunctiontoreturnthestepresponseofthemodeloutputs.Ifthemodelisinstate-spaceform,youalsocanusethisfunctiontoreturnthestepresponseofthemodelstates.Thisfunctionassumestheinitialmodelstatesarezero.Ifyoudonotspecifyanoutput,thisfunctioncreatesaplot.

>num=[1,1]; >den=[1,-1,3]; >H=tf(num,den); >t=[0:0.01:10]; >step(H,t);

lsim Createsthelinearsimulationplotofasystemmodel.Thisfunctioncalculatestheoutputofasystemmodelwhenasetofinputsexcitethemodel,usingdiscretesimulation.Ifyoudonotspecifyanoutput,thisfunctioncreatesaplot.

>t = [0:0.1:10] >u = sin(0.1*pi*t)' >lsim(SysIn, u, t)

Sys_order1 Constructsthecomponentsofafirst-ordersystemmodelbasedonagain,timeconstant,anddelaythatyouspecify.Youcanusethisfunctiontocreateeitherastate-spacemodeloratransferfunctionmodel,dependingontheoutputparametersyouspecify.

>K = 1; >tau = 1; >H = sys_order1(K, tau)

Sys_order2 Constructsthecomponentsofasecond-ordersystemmodelbasedonadampingratioandnaturalfrequencyyouspecify.Youcanusethisfunctiontocreateeitherastate-spacemodeloratransferfunctionmodel,dependingontheoutputparametersyouspecify.

>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)

damp Returnsthedampingratiosandnaturalfrequenciesofthepolesofasystemmodel.

>[dr, wn, p] = damp(SysIn)

pid Constructsaproportional-integral-derivative(PID)controllermodelineitherparallel,series,oracademicform.RefertotheLabVIEWControlDesignUserManualforinformationaboutthesethreeforms.

>Kc = 0.5; >Ti = 0.25; >SysOutTF = pid(Kc, Ti, 'academic');

conv Computestheconvolutionoftwovectorsormatrices. >C1 = [1, 2, 3]; >C2 = [3, 4]; >C = conv(C1, C2)

series ConnectstwosystemmodelsinseriestoproduceamodelSysSerwithinputandoutputconnectionsyouspecify

>Hseries = series(H1,H2)

feedback Connectstwosystemmodelstogethertoproduceaclosed-loopmodelusingnegativeorpositivefeedbackconnections

>SysClosed = feedback(SysIn_1, SysIn_2)

Page 77: MATLAB Course - Part III

70 AppendixA–MathScriptFunctions

MATLAB Course - Part III: Simulink and Advanced Topics in MATLAB

ss Constructsamodelinstate-spaceform.Youalsocanusethisfunctiontoconverttransferfunctionmodelstostate-spaceform.

>A = eye(2) >B = [0; 1] >C = B' >SysOutSS = ss(A, B, C)

ssinfo Returnsinformationaboutastate-spacesystemmodel. >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)

pade IncorporatestimedelaysintoasystemmodelusingthePadeapproximationmethod,whichconvertsallresiduals.Youmustspecifythedelayusingthesetfunction.Youalsocanusethisfunctiontocalculatecoefficientsofnumeratoranddenominatorpolynomialfunctionswithaspecifieddelay.

>[num, den] = pade(delay, order) >[A, B, C, D] = pade(delay, order)

bode CreatestheBodemagnitudeandBodephaseplotsofasystemmodel.Youalsocanusethisfunctiontoreturnthemagnitudeandphasevaluesofamodelatfrequenciesyouspecify.Ifyoudonotspecifyanoutput,thisfunctioncreatesaplot.

>num=[4]; >den=[2, 1]; >H = tf(num, den) >bode(H)

bodemag CreatestheBodemagnitudeplotofasystemmodel.Ifyoudonotspecifyanoutput,thisfunctioncreatesaplot.

>[mag, wout] = bodemag(SysIn) >[mag, wout] = bodemag(SysIn, [wmin wmax]) >[mag, wout] = bodemag(SysIn, wlist)

margin Calculatesand/orplotsthesmallestgainandphasemarginsofasingle-inputsingle-output(SISO)systemmodel.Thegainmarginindicateswherethefrequencyresponsecrossesat0decibels.Thephasemarginindicateswherethefrequencyresponsecrosses-180degrees.UsethemarginsfunctiontoreturnallgainandphasemarginsofaSISOmodel.

>num = [1] >den = [1, 5, 6] >H = tf(num, den) margin(H)

margins Calculatesallgainandphasemarginsofasingle-inputsingle-output(SISO)systemmodel.Thegainmarginsindicatewherethefrequencyresponsecrossesat0decibels.Thephasemarginsindicatewherethefrequencyresponsecrosses-180degrees.UsethemarginfunctiontoreturnonlythesmallestgainandphasemarginsofaSISOmodel.

>[gmf, gm, pmf, pm] = margins(H)

Formoredetailsaboutthesefunctions,type“helpcdt”togetanoverviewofallthefunctionsusedforControlDesignandSimulation.Fordetailedhelpaboutonespecificfunction,type“help<function_name>”.

Plotsfunctions:Herearesomeusefulfunctionsforcreatingplots:plot,figure,subplot,grid,axis,title,xlabel,ylabel,semilogx–formoreinformationabouttheplotsfunction,type“helpplots”.

Page 78: MATLAB Course - Part III

71

AppendixB:Mathematicscharacters

Page 79: MATLAB Course - Part III

Hans-PetterHalvorsen,M.Sc.

E-mail:[email protected]

Blog:http://home.hit.no/~hansha/

UniversityCollegeofSoutheastNorway

www.usn.no