Top Banner
University College of Southeast Norway MATLAB Part II: Modelling, Simulation & Control Hans-Petter Halvorsen, 2016.10.04 http://home.hit.no/~hansha
80

MATLAB Course - Part II: Modelling, Simulation and Control

Feb 09, 2022

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: MATLAB Course - Part II: Modelling, Simulation and Control

UniversityCollegeofSoutheastNorway

MATLAB PartII:Modelling,Simulation&Control Hans-PetterHalvorsen,2016.10.04

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

Page 2: MATLAB Course - Part II: Modelling, Simulation and Control

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

InPartIIofthecourse(PartII:Modelling,ControlandSimulation)youwilllearnhowtouseMATLABinModelling,ControlandSimulation.

YoumustgothroughMATLABCourse–PartI:IntroductiontoMATLABbeforeyoustart.

ThecourseconsistsoflotsofTasksyoushouldsolvewhilereadingthiscoursemanualandwatchingthevideosreferredtointhetext.

Makesuretobringyourheadphonesforthevideosinthiscourse.Thecourseconsistsofseveralshortvideosthatwillgiveyouanintroductiontothedifferenttopicsinthecourse.

Prerequisites

Page 3: MATLAB Course - Part II: Modelling, Simulation and Control

iii

Youshouldbefamiliarwithundergraduate-levelmathematicsandhaveexperiencewithbasiccomputeroperations.

WhatisMATLAB?MATLABisatoolfortechnicalcomputing,computationandvisualizationinanintegratedenvironment.MATLABisanabbreviationforMATrixLABoratory,soitiswellsuitedformatrixmanipulationandproblemsolvingrelatedtoLinearAlgebra.

MATLABisdevelopedbyTheMathWorks.MATLABisashort-termforMATrixLABoratory.MATLABisinuseworld-widebyresearchersanduniversities.Formoreinformation,seewww.mathworks.com

FormoreinformationaboutMATLAB,etc.,pleasevisithttp://home.hit.no/~hansha/

OnlineMATLABResources:MATLABBasics:

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

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 4: MATLAB Course - Part II: Modelling, Simulation and Control

iv

TableofContentsPreface......................................................................................................................................ii

TableofContents.....................................................................................................................iv

1 Introduction......................................................................................................................1

2 DifferentialEquationsandODESolvers............................................................................2

2.1 ODESolversinMATLAB.............................................................................................4

Task1: BacteriaPopulation.......................................................................................6

Task2: PassingParameterstothemodel..................................................................6

Task3: ODESolvers...................................................................................................8

Task4: 2.orderdifferentialequation........................................................................8

3 DiscreteSystems.............................................................................................................10

3.1 Discretization...........................................................................................................10

Task5: DiscreteSimulation.....................................................................................13

Task6: DiscreteSimulation–BacteriaPopulation..................................................13

Task7: Simulationwith2variables.........................................................................14

4 NumericalTechniques.....................................................................................................15

4.1 Interpolation............................................................................................................15

Task8: Interpolation................................................................................................17

4.2 CurveFitting............................................................................................................18

4.2.1 LinearRegression............................................................................................18

Task9: LinearRegression........................................................................................20

4.2.2 PolynomialRegression....................................................................................21

Task10: PolynomialRegression.............................................................................22

Page 5: MATLAB Course - Part II: Modelling, Simulation and Control

v TableofContents

MATLAB Course - Part II: Modelling, Simulation and Control

Task11: Modelfitting............................................................................................23

4.3 NumericalDifferentiation........................................................................................23

Task12: NumericalDifferentiation........................................................................28

4.3.1 DifferentiationonPolynomials........................................................................28

Task13: DifferentiationonPolynomials................................................................29

Task14: DifferentiationonPolynomials................................................................30

4.4 NumericalIntegration.............................................................................................30

Task15: NumericalIntegration.............................................................................33

4.4.1 IntegrationonPolynomials.............................................................................34

Task16: IntegrationonPolynomials.....................................................................34

5 Optimization....................................................................................................................35

Task17: Optimization............................................................................................38

Task18: Optimization-Rosenbrock'sBananaFunction........................................38

6 ControlSystemToolbox..................................................................................................40

7 TransferFunctions...........................................................................................................42

7.1 Introduction.............................................................................................................42

Task19: Transferfunction.....................................................................................44

7.2 SecondorderTransferFunction..............................................................................44

Task20: 2.orderTransferfunction........................................................................45

Task21: TimeResponse........................................................................................46

7.3 AnalysisofStandardFunctions................................................................................46

Task22: Integrator................................................................................................46

Task23: 1.ordersystem........................................................................................46

Task24: 2.ordersystem........................................................................................47

Task25: 2.ordersystem–SpecialCase................................................................48

8 State-spaceModels.........................................................................................................50

Page 6: MATLAB Course - Part II: Modelling, Simulation and Control

vi TableofContents

MATLAB Course - Part II: Modelling, Simulation and Control

8.1 Introduction.............................................................................................................50

8.2 Tasks........................................................................................................................52

Task26: State-spacemodel...................................................................................52

Task27: Mass-spring-dampersystem...................................................................52

Task28: BlockDiagram..........................................................................................53

8.3 DiscreteState-spaceModels...................................................................................54

Task29: Discretization...........................................................................................54

9 FrequencyResponse.......................................................................................................56

9.1 Introduction.............................................................................................................56

9.2 Tasks........................................................................................................................59

Task30: 1.ordersystem........................................................................................59

Task31: BodeDiagram..........................................................................................59

9.3 FrequencyresponseAnalysis..................................................................................60

9.3.1 LoopTransferFunction....................................................................................60

9.3.2 TrackingTransferFunction..............................................................................61

9.3.3 SensitivityTransferFunction...........................................................................61

Task32: FrequencyResponseAnalysis..................................................................62

9.4 StabilityAnalysisofFeedbackSystems...................................................................63

Task33: StabilityAnalysis......................................................................................65

10 AdditionalTasks..........................................................................................................66

Task34: ODESolvers.............................................................................................66

Task35: Mass-spring-dampersystem...................................................................66

Task36: NumericalIntegration.............................................................................67

Task37: State-spacemodel...................................................................................68

Task38: lsim..........................................................................................................68

AppendixA–MATLABFunctions............................................................................................70

Page 7: MATLAB Course - Part II: Modelling, Simulation and Control

vii TableofContents

MATLAB Course - Part II: Modelling, Simulation and Control

NumericalTechniques.........................................................................................................70

SolvingOrdinaryDifferentialEquations..........................................................................70

Interpolation...................................................................................................................70

CurveFitting....................................................................................................................70

NumericalDifferentiation...............................................................................................71

NumericalIntegration.....................................................................................................71

Optimization........................................................................................................................71

ControlandSimulation........................................................................................................72

Page 8: MATLAB Course - Part II: Modelling, Simulation and Control

1

1 IntroductionPart2:“Modelling,SimulationandControl”consistsofthefollowingtopics:

• DifferentialEquationsandODESolvers• DiscreteSystems• NumericalTechniques

o Interpolationo CurveFittingo NumericalDifferentiationo NumericalIntegration

• Optimization• ControlSystemToolbox• Transferfunctions• State-spacemodels• FrequencyResponse

Page 9: MATLAB Course - Part II: Modelling, Simulation and Control

2

2 DifferentialEquationsandODESolvers

MATLABhavelotsofbuilt-infunctionalityforsolvingdifferentialequations.MATLABincludesfunctionsthatsolveordinarydifferentialequations(ODE)oftheform:

𝑑𝑦𝑑𝑡 = 𝑓 𝑡, 𝑦 , 𝑦 𝑡' = 𝑦'

MATLABcansolvetheseequationsnumerically.

Higherorderdifferentialequationsmustbereformulatedintoasystemoffirstorderdifferentialequations.

Note!Differentnotationisused:

𝑑𝑦𝑑𝑡 = 𝑦( = 𝑦

Thisdocumentwillusethesedifferentnotationsinterchangeably.

Notalldifferentialequationscanbesolvedbythesametechnique,soMATLABofferslotsofdifferentODEsolversforsolvingdifferentialequations,suchasode45,ode23,ode113,etc.

Example:

Giventhefollowingdifferentialequation:

𝑥 = 𝑎𝑥

where 𝑎 = − ,- ,where 𝑇 isthetimeconstant

Note! 𝑥 = /0/1

Thesolutionforthedifferentialequationisfoundtobe:

𝑥 𝑡 = 𝑒31𝑥'

WeshallplotthesolutionforthisdifferentialequationusingMATLAB.

Set 𝑇 = 5 andtheinitialcondition 𝑥(0) = 1.

Page 10: MATLAB Course - Part II: Modelling, Simulation and Control

3 DifferentialEquationsandODESolvers

MATLAB Course - Part II: Modelling, Simulation and Control

WewillcreateascriptinMATLAB(.mfile)whereweplotthesolution 𝑥(𝑡) inthetimeinterval 0 ≤ 𝑡 ≤ 25

TheCodeisasfollows:

T = 5; a = -1/T; x0 = 1; t = [0:1:25] x = exp(a*t)*x0; plot(t,x); grid

ThisgivesthefollowingResults:

[EndofExample]

Thisworksfine,buttheproblemisthatwefirsthavetofindthesolutiontothedifferentialequation–insteadwecanuseoneofthebuilt-insolversforOrdinaryDifferentialEquations(ODE)inMATLAB.

Therearedifferentfunctions,suchasode23andode45.

Example:

Weusetheode23solverinMATLABforsolvingthedifferentialequation(“runmydiff.m”):

tspan = [0 25]; x0 = 1;

Page 11: MATLAB Course - Part II: Modelling, Simulation and Control

4 DifferentialEquationsandODESolvers

MATLAB Course - Part II: Modelling, Simulation and Control

[t,x] = ode23(@mydiff,tspan,x0); plot(t,x)

Where@mydiffisdefinedasafunctionlikethis(“mydiff.m”):

function dx = mydiff(t,x) a = -1/5; dx = a*x;

ThisgivesthesameresultsasshownintheplotaboveandMATLABhavesolvedthedifferentialequationforus(numerically).

Note!Youhavetoimplementitin2differentm.files,onem.filewhereyoudefinethedifferentialequationyouaresolving,andanother.mfilewhereyousolvetheequationusingtheode23solver.

[EndofExample]

2.1 ODESolversinMATLABAlloftheODEsolverfunctionsshareasyntaxthatmakesiteasytotryanyofthedifferentnumericalmethods,ifitisnotapparentwhichisthemostappropriate.Toapplyadifferentmethodtothesameproblem,simplychangetheODEsolverfunctionname.Thesimplestsyntax,commontoallthesolverfunctions,is:

[t,y] = solver(odefun,tspan,y0,options,…)

where“solver”isoneoftheODEsolverfunctions(ode23,ode45,etc.).

Note!Ifyoudon’tspecifytheresultingarray[t,y],thefunctioncreateaplotoftheresult.

‘odefun’isthefunctionhandler,whichisa“nickname”foryourfunctionthatcontainsthedifferentialequations.

Example:

Giventhedifferentialequations:

𝑑𝑦𝑑𝑡 = 𝑥

𝑑𝑥𝑑𝑡 = −𝑦

InMATLAByoudefineafunctionforthesedifferentialequations:

function dy=mydiff(t,y)

Page 12: MATLAB Course - Part II: Modelling, Simulation and Control

5 DifferentialEquationsandODESolvers

MATLAB Course - Part II: Modelling, Simulation and Control

dy(1) = y(2); dy(2) = -y(1); dy = [dy(1); dy(2)];

Note!Sincenumbersofequationsismorethanone,weneedtousevectors!!

Usingtheode45functiongivesthefollowingcode:

[t,y] = ode45(@mydiff, [-1,1], [1,1]); plot(t,y) title('solution of dy/dt=x and dx/dt=-y') legend('y', 'x')

Theequationsaresolvedinthetimespan [−11] withinitialvalues [1, 1].

Thisgivesthefollowingplot:

Tomakeitmoreclearly,wecanrewritetheequations(setting 𝑥, = 𝑥, 𝑥> = 𝑦):

𝑑𝑥,𝑑𝑡 = −𝑥>

𝑑𝑥>𝑑𝑡 = 𝑥,

Thecodeforthedifferentialequations(“mydiff.m”):

function dxdt = mydiff(t,x) dxdt(1) = -x(2); dxdt(2) = x(1);

Page 13: MATLAB Course - Part II: Modelling, Simulation and Control

6 DifferentialEquationsandODESolvers

MATLAB Course - Part II: Modelling, Simulation and Control

dxdt = dxdt';

Note!Thefunctionmydiffmustreturnacolumnvector,that’swhyweneedtotransposeit.

Thenweusetheodesolvertosolvethedifferentialequations(“run_mydiff.m”):

tspan = [-1,1]; x0 = [1,1]; [t,x] = ode45(@mydiff, tspan, x0); plot (t,x) legend('x1', 'x2')

Thesolutionwillbethesame.

[EndofExample]

Task1: BacteriaPopulation

Inthistaskwewillsimulateasimplemodelofabacteriapopulationinajar.

Themodelisasfollows:

birthrate=bx

deathrate=px2

Thenthetotalrateofchangeofbacteriapopulationis:

𝑥 = 𝑏𝑥 − 𝑝𝑥>

Setb=1/hourandp=0.5bacteria-hour

Note! 𝑥 = /0/1

→Simulate(i.e.,createaplot)thenumberofbacteriainthejarafter1hour,assumingthatinitiallythereare100bacteriapresent.

Howmanybacteriaarepresentafter1hour?

[EndofTask]

Task2: PassingParameterstothemodel

Giventhefollowingsystem:

Page 14: MATLAB Course - Part II: Modelling, Simulation and Control

7 DifferentialEquationsandODESolvers

MATLAB Course - Part II: Modelling, Simulation and Control

𝑥 = 𝑎𝑥 + 𝑏

where 𝑎 = − ,- ,where 𝑇 isthetimeconstant

Inthiscasewewanttopass 𝑎 and 𝑏 asparameters,tomakeiteasytobeabletochangevaluesfortheseparameters.

Wesetinitialcondition𝑥(0) = 1 and 𝑇 = 5.

Thefunctionforthedifferentialequationis:

function dx = mysimplediff(t,x,param) % My Simple Differential Equation a = param(1); b = param(2); dx = a*x+b;

Thenwesolveandplottheequationusingthiscode:

tspan = [0 25]; x0 = 1; a = -1/5; b = 1; param = [a b]; [t,y] = ode45(@mysimplediff, tspan, x0,[], param); plot(t,y)

Bydoingthis,itisveryeasytochangesvaluesfortheparameters 𝑎 and 𝑏 withoutchangingthecodeforthedifferentialequation.

Note!Weneedtousethe5.argumentintheODEsolverfunctionforthis.The4.argumentisforspecialoptionsandisnormallysetto“[]”,i.e.,nooptions.

Theresultfromthesimulationis:

Page 15: MATLAB Course - Part II: Modelling, Simulation and Control

8 DifferentialEquationsandODESolvers

MATLAB Course - Part II: Modelling, Simulation and Control

→Writethecodeabove

ReadmoreaboutthedifferentsolversthatexistsintheHelpsysteminMATLAB

[EndofTask]

Task3: ODESolvers

Usetheode23functiontosolveandplottheresultsofthefollowingdifferentialequationintheinterval [𝑡', 𝑡L]:

𝒘( + 𝟏. 𝟐 + 𝒔𝒊𝒏𝟏𝟎𝒕 𝒘 = 𝟎, 𝑡' = 0, 𝑡L = 5,𝑤 𝑡' = 1

Note! 𝑤( = /W/1

[EndofTask]

Task4: 2.orderdifferentialequation

Usetheode23/ode45functiontosolveandplottheresultsofthefollowingdifferentialequationintheinterval [𝑡', 𝑡L]:

𝟏 + 𝒕𝟐 𝒘 + 𝟐𝒕𝒘 + 𝟑𝒘 = 𝟐, 𝑡' = 0, 𝑡L = 5,𝑤 𝑡' = 0,𝑤 𝑡' = 1

Note! 𝑤 = /YW/1Y

Page 16: MATLAB Course - Part II: Modelling, Simulation and Control

9 DifferentialEquationsandODESolvers

MATLAB Course - Part II: Modelling, Simulation and Control

Note!Higherorderdifferentialequationsmustbereformulatedintoasystemoffirstorderdifferentialequations.

Tip1:Reformulatethedifferentialequationso 𝑤 isaloneontheleftside.

Tip2:Set:

𝑤 = 𝑥,

𝑤 = 𝑥>

[EndofTask]

Page 17: MATLAB Course - Part II: Modelling, Simulation and Control

10

3 DiscreteSystemsMATLABhasbuilt-inpowerfulfeaturesforsimulationofcontinuousdifferentialequationsanddynamicsystems.

SometimeswewanttoorneedtodiscretizeacontinuoussystemandthensimulateitinMATLAB.

Whendealingwithcomputersimulation,weneedtocreateadiscreteversionofoursystem.Thismeansweneedtomakeadiscreteversionofourcontinuousdifferentialequations.Actually,thebuilt-inODEsolversinMATLABusedifferentdiscretizationmethods.Interpolation,CurveFitting,etc.isalsobasedonasetofdiscretevalues(datapointsormeasurements).ThesamewithNumericalDifferentiationandNumericalIntegration,etc.

Belowweseeacontinuoussignalvsthediscretesignalforagivensystemwithdiscretetimeinterval 𝑇Z = 0.1𝑠.

3.1 DiscretizationInordertodiscretizeacontinuousmodeltherearelotsofdifferentmethodstouse.OneofthesimplestisEulerForwardmethod:

𝑥 ≈𝑥]^, − 𝑥]

𝑇Z

where 𝑇Z isthesamplingtime.

Page 18: MATLAB Course - Part II: Modelling, Simulation and Control

11 DiscreteSystems

MATLAB Course - Part II: Modelling, Simulation and Control

Lotsofotherdiscretizationmethodsdoexists,suchas“Eulerbackward”,ZeroOrderHold(ZOH),Tustin’smethod,etc.

Asshowninapreviouschapter,MATLABhavelotsofbuilt-infunctionsforsolvingdifferentialequationsnumerically,butherewewillcreateourowndiscretemodel.

Example:

Giventhefollowingdifferentialequation:

𝑥 = −𝑎𝑥 + 𝑏𝑢

Note!

𝑥 isthesameas /0/1

Where:

𝑥 -Processvariable,e.g.,Level,Pressure,Temperature,etc.

𝑢 -Inputvariable,e.g.,ControlSignalfromtheController

𝑎, 𝑏 -Constants

Westartwithfindingthediscretedifferentialequation.

Wecanusee.g.,theEulerApproximation:

𝑥 ≈𝑥]^, − 𝑥]

𝑇Z

Page 19: MATLAB Course - Part II: Modelling, Simulation and Control

12 DiscreteSystems

MATLAB Course - Part II: Modelling, Simulation and Control

𝑇Z -SamplingInterval

Thenweget:

𝑥]^, − 𝑥]𝑇Z

= −𝑎𝑥] + 𝑏𝑢]

Thisgivesthefollowingdiscretedifferentialequation:

𝑥]^, = 1 − 𝑇Z𝑎 𝑥] + 𝑇Z𝑏𝑢]

Nowwearereadytosimulatethesystem

Weset 𝑎 = 0.25, 𝑏 = 2 and 𝑢 = 1 (Youcanexplorewithothervaluesonyourown)

TheCodecanbewrittenasfollows:

% Simulation of discrete model clear, clc % Model Parameters a = 0.25;b = 2; % Simulation Parameters Ts = 0.1; %s Tstop = 30; %s uk = 1; % Step Response x(1) = 0; % Simulation for k=1:(Tstop/Ts) x(k+1) = (1-a*Ts).*x(k) + Ts*b*uk; end % Plot the Simulation Results k=0:Ts:Tstop; plot(k,x) grid on

ThisgivesthefollowingResults:

Page 20: MATLAB Course - Part II: Modelling, Simulation and Control

13 DiscreteSystems

MATLAB Course - Part II: Modelling, Simulation and Control

[EndofExample]

Task5: DiscreteSimulation

Giventhefollowingdifferentialequation:

𝑥 = 𝑎𝑥

where 𝑎 = − ,- ,where 𝑇 isthetimeconstant

Note! 𝑥 = /0/1

FindthediscretedifferentialequationandplotthesolutionforthissystemusingMATLAB.

Set 𝑇 = 5andtheinitialcondition 𝑥(0) = 1.

CreateascriptinMATLAB(.mfile)whereweplotthesolution 𝑥(𝑘).

[EndofTask]

Task6: DiscreteSimulation–BacteriaPopulation

Inthistaskwewillsimulateasimplemodelofabacteriapopulationinajar.

Themodelisasfollows:

Page 21: MATLAB Course - Part II: Modelling, Simulation and Control

14 DiscreteSystems

MATLAB Course - Part II: Modelling, Simulation and Control

birthrate=bx

deathrate=px2

Thenthetotalrateofchangeofbacteriapopulationis:

𝑥 = 𝑏𝑥 − 𝑝𝑥>

Setb=1/hourandp=0.5bacteria-hour

Wewillsimulatethenumberofbacteriainthejarafter1hour,assumingthatinitiallythereare100bacteriapresent.

→FindthediscretemodelusingtheEulerForwardmethodbyhandandimplementandsimulatethesysteminMATLABusingaForLoop.

[EndofTask]

Task7: Simulationwith2variables

Giventhefollowingsystem

𝑑𝑥,𝑑𝑡 = −𝑥>

𝑑𝑥>𝑑𝑡 = 𝑥,

FindthediscretesystemandsimulatethediscretesysteminMATLAB.

Solvetheequations,e.g.,inthetimespan [−11] withinitialvalues [1, 1].

[EndofTask]

Page 22: MATLAB Course - Part II: Modelling, Simulation and Control

15

4 NumericalTechniquesInthepreviouschapterweinvestigatedhowtosolvedifferentialequationsnumerically,inthischapterwewilltakeacloserlookatsomeothernumericaltechniquesofferedbyMATLAB,suchasinterpolation,curve-fitting,numericaldifferentiationsandintegrations.

4.1 InterpolationInterpolationisusedtoestimatedatapointsbetweentwoknownpoints.ThemostcommoninterpolationtechniqueisLinearInterpolation.

InMATLABwecanusetheinterp1function.

Example:

Giventhefollowingdata:

x y0 151 102 93 64 25 0

Wewillfindtheinterpolatedvaluefor 𝑥 = 3.5.

ThefollowingMATLABcodewilldothis:

x=0:5; y=[15, 10, 9, 6, 2, 0]; plot(x,y ,'-o') % Find interpolated value for x=3.5 new_x=3.5; new_y = interp1(x,y,new_x)

Theansweris4,fromtheplotbelowweseethisisagoodguess:

Page 23: MATLAB Course - Part II: Modelling, Simulation and Control

16 NumericalTechniques

MATLAB Course - Part II: Modelling, Simulation and Control

[EndofExample]

Thedefaultislinearinterpolation,butthereareothertypesavailable,suchas:

• linear• nearest• spline• cubic• etc.

Type“helpinterp1”inordertoreadmoreaboutthedifferentoptions.

Example:

Inthisexamplewewilluseasplineinterpolationonthesamedataasintheexampleabove.

x=0:5; y=[15, 10, 9,6, 2, 0]; new_x=0:0.2:5; new_y=interp1(x,y,new_x, 'spline') plot(x,y, new_x, new_y, '-o')

Theresultisasweplotboththeoriginalpointandtheinterpolatedpointsinthesamegraph:

Page 24: MATLAB Course - Part II: Modelling, Simulation and Control

17 NumericalTechniques

MATLAB Course - Part II: Modelling, Simulation and Control

Weseethisresultin2differentlines.

[EndofExample]

Task8: Interpolation

Giventhefollowingdata:

Temperature,T[oC] Energy,u[KJ/kg]100 2506.7150 2582.8200 2658.1250 2733.7300 2810.4400 2967.9500 3131.6

PlotuversusT.Findtheinterpolateddataandplotitinthesamegraph.Testoutdifferentinterpolationtypes.Discusstheresults.Whatkindofinterpolationisbestinthiscase?

Whatistheinterpolatedvalueforu=2680.78KJ/kg?

[EndofTask]

Page 25: MATLAB Course - Part II: Modelling, Simulation and Control

18 NumericalTechniques

MATLAB Course - Part II: Modelling, Simulation and Control

4.2 CurveFittingIntheprevioussectionwefoundinterpolatedpoints,i.e.,wefoundvaluesbetweenthemeasuredpointsusingtheinterpolationtechnique.Itwouldbemoreconvenienttomodelthedataasmathematicalfunction 𝑦 = 𝑓(𝑥).Thenwecouldeasilycalculateanydatawewantbasedonthismodel.

MATLABhasbuilt-incurvefittingfunctionsthatallowsustocreateempiricdatamodel.Itisimportanttohaveinmindthatthesemodelsaregoodonlyintheregionwehavecollecteddata.

HerearesomeofthefunctionsavailableinMATLABusedforcurvefitting:

Function Description Examplepolyfit P=POLYFIT(X,Y,N)findsthecoefficientsofapolynomialP(X)of

degreeNthatfitsthedataYbestinaleast-squaressense.Pisa rowvectoroflengthN+1containingthepolynomialcoefficientsindescendingpowers,P(1)*X^N+P(2)*X^(N-1)+...+P(N)*X+P(N+1).

>>polyfit(x,y,1)

polyval Evaluatepolynomial.Y=POLYVAL(P,X)returnsthevalueofapolynomialPevaluatedatX.PisavectoroflengthN+1whoseelementsarethecoefficientsofthepolynomialindescendingpowers.Y=P(1)*X^N+P(2)*X^(N-1)+...+P(N)*X+P(N+1)

ThesetechniquesuseapolynomialofdegreeNthatfitsthedataYbestinaleast-squaressense.

Apolynomialisexpressedas:

𝑝 𝑥 = 𝑝,𝑥b + 𝑝>𝑥bc, + ⋯+ 𝑝b𝑥 +𝑝b^,

where 𝑝,, 𝑝>, 𝑝e, … arethecoefficientsofthepolynomial.

MATLABrepresentspolynomialsasrowarrayscontainingcoefficientsorderedbydescendingpowers.

4.2.1 LinearRegression

Herewewillcreatealinearmodelofourdataontheform:

𝑦 = 𝑎𝑥 + 𝑏

Thisisactuallyapolynomialof1.order

Example:

Giventhefollowingdata:

Page 26: MATLAB Course - Part II: Modelling, Simulation and Control

19 NumericalTechniques

MATLAB Course - Part II: Modelling, Simulation and Control

x y0 151 102 93 64 25 0

Wewillfindthemodelontheform:

𝑦 = 𝑎𝑥 + 𝑏

WewillusethepolyfitfunctioninMATLAB.

Thefollowingcodewillsolveit:

x=[0, 1, 2, 3, 4 ,5]; y=[15, 10, 9, 6, 2 ,0]; n=1; % 1.order polynomial p = polyfit(x,y,n)

Theansweris:

ans=

-2.9143 14.2857

Thisgivesthefollowingmodel:

𝑦 = −2.9143𝑥 + 14.2857

Wecanalsoplotthemeasureddataandthemodelinthesameplot:

x=[0, 1, 2, 3, 4 ,5]; y=[15, 10, 9, 6, 2 ,0]; n=1; % 1.order polynomial p=polyfit(x,y,n); a=p(1); b=p(2); ymodel=a*x+b; plot(x,y,'o',x,ymodel)

Thisgivesthefollowingplot:

Page 27: MATLAB Course - Part II: Modelling, Simulation and Control

20 NumericalTechniques

MATLAB Course - Part II: Modelling, Simulation and Control

Weseethisgivesagoodmodelbasedonthedataavailable.

[EndofExample]

Task9: LinearRegression

Giventhefollowingdata:

Temperature,T[oC] Energy,u[KJ/kg]100 2506.7150 2582.8200 2658.1250 2733.7300 2810.4400 2967.9500 3131.6

PlotuversusT.

Findthelinearregressionmodelfromthedata

𝑦 = 𝑎𝑥 + 𝑏

Plotitinthesamegraph.

[EndofTask]

Page 28: MATLAB Course - Part II: Modelling, Simulation and Control

21 NumericalTechniques

MATLAB Course - Part II: Modelling, Simulation and Control

4.2.2 PolynomialRegression

Intheprevioussectionweusedlinearregressionwhichisa1.orderpolynomial.Inthissectionwewillstudyhigherorderpolynomials.

Inpolynomialregressionwewillfindthefollowingmodel:

𝑦 𝑥 = 𝑎'𝑥b + 𝑎,𝑥bc, + ⋯+ 𝑎bc,𝑥 +𝑎b

Example:

Giventhefollowingdata:

x y0 151 102 93 64 25 0

Wewillfoundthemodeloftheform:

𝑦 𝑥 = 𝑎'𝑥b + 𝑎,𝑥bc, + ⋯+ 𝑎bc,𝑥 +𝑎b

WewillusethepolyfitandpolyvalfunctionsinMATLABandcomparethemodelsusingdifferentordersofthepolynomial.

Wewillinvestigatemodelsof2.order,3.order,4.orderand5.order.Wehaveonly6datapoints,soamodelwithorderhigherthan5willmakenosense.

WeuseaForloopinordertocreatemodelsof2,3,4and5.order.

Thecodeisasfollows:

x=[0, 1, 2, 3, 4 ,5]; y=[15, 10, 9, 6, 2 ,0]; for n=2:5 %From order 2 to 5 p=polyfit(x,y,n) ymodel=polyval(p,x); subplot(2,2,n-1) plot(x,y,'o',x,ymodel) title(sprintf('Model of order %d', n)); end

Page 29: MATLAB Course - Part II: Modelling, Simulation and Control

22 NumericalTechniques

MATLAB Course - Part II: Modelling, Simulation and Control

Thepolyfitgivesthefollowingpolynomials:

p = 0.0536 -3.1821 14.4643 p = -0.0648 0.5397 -4.0701 14.6587 p = 0.1875 -1.9398 6.2986 -9.4272 14.9802 p = -0.0417 0.7083 -4.2083 10.2917 -11.7500 15.0000

Usingthevalues,wegetthefollowingmodels:

𝑦> 𝑥 ≈ 0.05𝑥> − 3.2𝑥 + 14.5

𝑦e 𝑥 ≈ −0.065𝑥e + 0.5𝑥> − 4𝑥 + 14.7

𝑦l 𝑥 ≈ 0.2𝑥l − 1.9𝑥e + 6.3𝑥> − 9.4𝑥 + 15

𝑦m 𝑥 ≈ −0.04𝑥m + 0.7𝑥l − 4.2𝑥e + 10.3𝑥> − 11.8𝑥 + 15

Thisgivesthefollowingresults:

Asexpected,thehigherordermodelsmatchthedatabetterandbetter.

Note!Thefifthordermodelmatchesexactlybecausetherewereonlysixdatapointsavailable.

[EndofExample]

Task10: PolynomialRegression

Page 30: MATLAB Course - Part II: Modelling, Simulation and Control

23 NumericalTechniques

MATLAB Course - Part II: Modelling, Simulation and Control

Giventhefollowingdata:

x y10 2320 4530 6040 8250 11160 14070 16780 19890 200100 220

→UsethepolyfitandpolyvalfunctionsinMATLABandcomparethemodelsusingdifferentordersofthepolynomial.

Usesubplotsandmakesuretoaddtitles,etc.

[EndofTask]

Task11: Modelfitting

Giventhefollowingdata:

Height,h[ft] Flow,f[ft^3/s]0 01.7 2.61.95 3.62.60 4.032.92 6.454.04 11.225.24 30.61

→Createa1.(linear),2.(quadratic)and3.order(cubic)model.Whichgivesthebestmodel?Plottheresultinthesameplotandcomparethem.Addxlabel,ylabel,titleandalegendtotheplotandusedifferentlinestylessotheusercaneasilyseethedifference.

[EndofTask]

4.3 NumericalDifferentiationThederivativeofafunction 𝑦 = 𝑓(𝑥) isameasureofhowychangeswithx.

Page 31: MATLAB Course - Part II: Modelling, Simulation and Control

24 NumericalTechniques

MATLAB Course - Part II: Modelling, Simulation and Control

Assumethefollowing:

Thenwehavethefollowingdefinition:

MATLABisanumericallanguageanddonotperformsymbolicmathematics(...well,thatisnotentirelytruebecausethereisSymbolicToolboxavailableforMATLAB,butthisToolkitwillnotbeusedinthiscourse).

MATLABoffersfunctionsfornumericaldifferentiation,e.g.:

Function Description Examplediff Differenceandapproximatederivative.DIFF(X),foravectorX,

is[X(2)-X(1) X(3)-X(2)...X(n)-X(n-1)].>> dydx_num=diff(y)./diff(x);

polyder Differentiatepolynomial.POLYDER(P)returnsthederivativeofthepolynomialwhosecoefficientsaretheelementsofvectorP.POLYDER(A,B)returnsthederivativeofpolynomialA*B.

>>p=[1,2,3]; >>polyder(p)

Anumericalapproachtothederivativeofafunction 𝑦 = 𝑓(𝑥)is:

𝑑𝑦𝑑𝑥 =

∆𝑦∆𝑥 =

𝑦> − 𝑦,𝑥> − 𝑥,

Page 32: MATLAB Course - Part II: Modelling, Simulation and Control

25 NumericalTechniques

MATLAB Course - Part II: Modelling, Simulation and Control

Thisapproximationofthederivativecorrespondstotheslopeofeachlinesegmentusedtoconnecteachdatapointthatexists.Anexampleisshownbelow:

Example:

WewilluseNumericalDifferentiationtofind /o/0 onthefollowingfunction:

𝑦 = 𝑥>

basedonthedatapoints(x=-2:2):

x y-2 4-1 10 01 12 4

First,wewillplotthedatapointstogetherwiththerealfunction 𝑦 = 𝑥> usingthefollowingcode:

x=-2:0.1:2; y=x.^2; plot(x,y) hold on x=-2:2; y=x.^2; plot(x,y, '-oc')

Page 33: MATLAB Course - Part II: Modelling, Simulation and Control

26 NumericalTechniques

MATLAB Course - Part II: Modelling, Simulation and Control

Thisgivesthefollowingplot:

Thenwewanttofindthederivative /o/0

Weknowthattheexactsolutionis:

𝑑𝑦𝑑𝑥 = 2𝑥

Forthevaluesgiveninthetablewehave:

Wewillusethistocomparetheresultsfromthenumericaldifferentiationwiththeexactsolution(seeabove).

Thecodeisasfollows:

x=-2:2; y=x.^2;

Page 34: MATLAB Course - Part II: Modelling, Simulation and Control

27 NumericalTechniques

MATLAB Course - Part II: Modelling, Simulation and Control

dydx_num=diff(y)./diff(x); dydx_exact=2*x; dydx=[[dydx_num, NaN]', dydx_exact']

Thisgivesthefollowingresults(leftcolumnisfromthenumericalderivation,whiletherightcolumnisfromtheexactderivation):

dydx = -3 -4 -1 -2 1 0 3 2 NaN 4

Note!NaNisaddedtothevectorwithnumericaldifferentiationinordertogetthesamelengthofthevectors.

Ifweplotthederivatives(numericalandexact),weget:

Ifweincreasethenumberofdatapoints(x=-2:0.1:2)wegetabetterresult:

Page 35: MATLAB Course - Part II: Modelling, Simulation and Control

28 NumericalTechniques

MATLAB Course - Part II: Modelling, Simulation and Control

[EndofExample]

Task12: NumericalDifferentiation

Giventhefollowingequation:

𝑦 = 𝑥e + 2𝑥> − 𝑥 + 3

Find /o/0 analytically(use“penandpaper”).

Defineavectorxfrom-5to+5andusethedifffunctiontoapproximatethederivativeywith

respecttox(∆o∆0).

Comparethedataina2Darrayand/orplotboththeexactvalueof /o/0 andthe

approximationinthesameplot.

Increasenumberofdatapointtoseeifthereareanydifference.

Dothesameforthefollowingfunctions:

𝑦 = sin(𝑥)

𝑦 = 𝑥m − 1

[EndofTask]

4.3.1 DifferentiationonPolynomials

Page 36: MATLAB Course - Part II: Modelling, Simulation and Control

29 NumericalTechniques

MATLAB Course - Part II: Modelling, Simulation and Control

Apolynomialisexpressedas:

𝑝 𝑥 = 𝑝,𝑥b + 𝑝>𝑥bc, + ⋯+ 𝑝b𝑥 +𝑝b^,

where 𝑝,, 𝑝>, 𝑝e, … arethecoefficientsofthepolynomial.

ThedifferentiationofthePolynomialwillbe:

𝑝 𝑥 ( = 𝑝,𝑛𝑥bc, + 𝑝>(𝑛 − 1)𝑥bc> + ⋯+ 𝑝b

Example

Giventhepolynomial

𝑝 𝑥 = 2 + 𝑥e

Wecanrewritethepolynomiallikethis:

𝑝 𝑥 = 1 ∙ 𝑥e + 0 ∙ 𝑥> + 0 ∙ 𝑥 + 2

ThepolynomialisdefinedinMATLABas:

>> p=[1, 0, 0, 2]

Weknowthat: 𝑝( = 3𝑥>

Thecodeisasfollows

>> p=[1, 0, 0, 2] p = 1 0 0 2 >> polyder(p) ans = 3 0 0

Whichiscorrect,because

𝑝 𝑥 ( = 3 ∙ 𝑥> + 0 ∙ 𝑥> + 0

withthecoefficients:

𝑝, = 3, 𝑝> = 0, 𝑝e = 0

Andthisiswrittenasavector 3 0 0 inMATLAB.

[EndofExample]

Task13: DifferentiationonPolynomials

Considerthefollowingequation:

Page 37: MATLAB Course - Part II: Modelling, Simulation and Control

30 NumericalTechniques

MATLAB Course - Part II: Modelling, Simulation and Control

𝑦 = 𝑥e + 2𝑥> − 𝑥 + 3

UseDifferentiationonthePolynomialtofind /o/0

[EndofTask]

Task14: DifferentiationonPolynomials

Findthederivativefortheproduct:

3𝑥> + 6𝑥 + 9 𝑥> + 2𝑥

Usethepolyder(a,b)function.

Anotherapproachistousedefineistofirstusetheconv(a,b)functiontofindthetotalpolynomial,andthenusepolyder(p)function.

Trybothmethods,toseeifyougetthesameanswer.

[EndofTask]

4.4 NumericalIntegrationTheintegralofafunction 𝑓(𝑥) isdenotedas:

𝑓 𝑥 𝑑𝑥t

3

Anintegralcanbeseenastheareaunderacurve.Given 𝑦 = 𝑓(𝑥) theapproximationoftheArea(A)underthecurvecanbefounddividingtheareaupintorectanglesandthensummingthecontributionfromalltherectangles:

𝐴 = 𝑥v^, − 𝑥v ∙ 𝑦v^, + 𝑦v /2bc,

vx,

Thisisknownasthetrapezoidrule.

Weapproximatetheintegralbyusingntrapezoidsformedbyusingstraightlinesegmentsbetweenthepoints (𝑥vc,, 𝑦vc,) and (𝑥v, 𝑦v) for 1 ≤ 𝑖 ≤ 𝑛asshowninthefigurebelow:

Page 38: MATLAB Course - Part II: Modelling, Simulation and Control

31 NumericalTechniques

MATLAB Course - Part II: Modelling, Simulation and Control

Theareaofatrapezoidisobtainedbyaddingtheareaofarectangleandatriangle:

MATLABoffersfunctionsfornumericalintegration,suchas:

Function Description Examplediff Differenceandapproximatederivative.DIFF(X),foravectorX,

is[X(2)-X(1) X(3)-X(2)...X(n)-X(n-1)].>> dydx_num=diff(y)./diff(x);

quad Numericallyevaluateintegral,adaptiveSimpsonquadrature.Q=QUAD(FUN,A,B)triestoapproximatetheintegralofcalar-valuedfunctionFUNfromAtoB.FUNisafunctionhandle.ThefunctionY=FUN(X)shouldacceptavectorargumentXandreturnavectorresultY,theintegrandevaluatedateachelementofX.UsesadaptiveSimpsonquadraturemethod

>>

quadl Sameasquad,butusesadaptiveLobattoquadraturemethod >>

polyint Integratepolynomialanalytically. POLYINT(P,K)returnsapolynomialrepresentingtheintegralofpolynomialP,usingascalarconstantofintegrationK.

Example:

Giventhefunction:

𝑦 = 𝑥>

Page 39: MATLAB Course - Part II: Modelling, Simulation and Control

32 NumericalTechniques

MATLAB Course - Part II: Modelling, Simulation and Control

Weknowthattheexactsolutionis:

𝑥>𝑑𝑥 =𝑎e

3

3

'

Theintegralfrom0to1is:

𝑥>𝑑𝑥 =13

,

'≈ 0.3333

WewillusethetrapezoidruleandthedifffunctioninMATLABtosolvethenumericalintegralof 𝑥> from0to1.

TheMATLABcodeforthisis:

x=0:0.1:1; y=x.^2; avg_y = y(1:length(x)-1) + diff(y)/2; A = sum(diff(x).*avg_y)

Note!

Thefollowingtwolinesofcode

avg_y = y(1:length(x)-1) + diff(y)/2;

A = sum(diff(x).*avg_y)

Implementsthisformula,knownasthetrapezoidrule:

𝐴 = 𝑥v^, − 𝑥v ∙ 𝑦v^, + 𝑦v /2bc,

vx,

Page 40: MATLAB Course - Part II: Modelling, Simulation and Control

33 NumericalTechniques

MATLAB Course - Part II: Modelling, Simulation and Control

Theresultfromtheapproximationis:

A = 0.3350

Ifweusethefunctionsquadweget:

quad('x.^2', 0,1) ans = 0.3333

Ifweusethefunctionsquadlweget:

quadl('x.^2', 0,1) ans = 0.3333

[EndofExample]

Task15: NumericalIntegration

Usediff,quadandquadlonthefollowingequation:

𝑦 = 𝑥e + 2𝑥> − 𝑥 + 3

Findtheintegralofywithrespecttox,evaluatedfrom-1to1

Comparethedifferentmethods.

Theexactsolutionis:

(𝑥e + 2𝑥> − 𝑥 + 3)𝑑𝑥t

3=

𝑥l

4 +2𝑥e

3 −𝑥>

2 + 3𝑥3

t

=14 𝑏l − 𝑎l +

23 𝑏e − 𝑎e −

12 𝑏> − 𝑎> + 3(𝑏 − 𝑎)

Comparetheresultwiththeexactsolution.

Repeatthetaskforthefollowingfunctions:

𝑦 = sin 𝑥

𝑦 = 𝑥m − 1

[EndofTask]

Page 41: MATLAB Course - Part II: Modelling, Simulation and Control

34 NumericalTechniques

MATLAB Course - Part II: Modelling, Simulation and Control

4.4.1 IntegrationonPolynomials

Apolynomialisexpressedas:

𝑝 𝑥 = 𝑝,𝑥b + 𝑝>𝑥bc, + ⋯+ 𝑝b𝑥 +𝑝b^,

where 𝑝,, 𝑝>, 𝑝e, … arethecoefficientsofthepolynomial.

InMATLABwecanusethepolyintfunctiontoperformintegrationonpolynomials.Thisfunctionworksthesamewayasthepolyderfunctionwhichperformsdifferentiationonpolynomials.

Task16: IntegrationonPolynomials

Considerthefollowingequation:

𝑦 = 𝑥e + 2𝑥> − 𝑥 + 3

Findtheintegralof 𝑦 withrespectto 𝑥 ( 𝑦𝑑𝑥)usingMATLAB.

[EndofTask]

Page 42: MATLAB Course - Part II: Modelling, Simulation and Control

35

5 OptimizationOptimizationisimportantincontrolandsimulationapplications.Optimizationisbasedonfindingtheminimumofagivencriteriafunction.

InMATLABwecanusethefminbndandfminsearchfunctions.Wewilltakeacloserlookofhowtousethesefunctions.

Function Description Examplefminbnd X=FMINBND(FUN,x1,x2)attemptstofindalocalminimizer

XofthefunctionFUNintheintervalx1<X<x2.FUNisafunctionhandle. FUNacceptsscalarinputXandreturnsascalarfunctionvalueFevaluatedatX.FUNcanbespecifiedusing@.FMINBNDisasingle-variableboundednonlinearfunctionminimization.

>> x = fminbnd(@cos,3,4) x = 3.1416

fminsearch X=FMINSEARCH(FUN,X0)startsatX0andattemptstofindalocalminimizerXofthefunctionFUN.FUNisafunctionhandle. FUNacceptsinputXandreturnsascalarfunctionvalueFevaluatedatX.X0canbeascalar,vectorormatrix.FUNcanbespecifiedusing@.FMINSEARCHisamultidimensionalunconstrainednonlinearfunctionminimization.

>> x = fminsearch(@sin,3) x = 4.7124

Example:

Giventhefollowingfunction:

𝑓 𝑥 = 𝑥> + 2𝑥 + 1

Wewillusefminbndtofindtheminimumofthefunction.

Weplotthefunction:

Page 43: MATLAB Course - Part II: Modelling, Simulation and Control

36 Optimization

MATLAB Course - Part II: Modelling, Simulation and Control

WewritethefollowingMATLABScript:

x = -5:1:5; f = mysimplefunc(x); plot(x, f) x_min = fminbnd(@mysimplefunc, -5, 5)

wherethefunction(mysimplefunc.m)isdefinedlikethis:

function f = mysimplefunc(x) f = x.^2 + 2.*x + 1;

Thisgives:

x_min =

-1

→Theminimumofthefunctionis-1.Thiscanalsobeshownfromtheplot.

[EndofExample]

Note!Ifafunctionhasmorethanonevariable,weneedtousethefminsearchfunction.

Example:

Giventhefollowingfunction:

𝑓 𝑥, 𝑦 = 2(𝑥 − 1)> + 𝑥 − 2 +(𝑦 − 2)> + 𝑦

Page 44: MATLAB Course - Part II: Modelling, Simulation and Control

37 Optimization

MATLAB Course - Part II: Modelling, Simulation and Control

Wewillusefminsearchtofindtheminimumofthefunction.

TheMATLABCodecanbewrittenlikethis:

[x,fval] = fminsearch(@myfunc, [1;1])

wherethefunctionisdefinedlikethis:

function f = myfunc(x) f = 2*(x(1)-1).^2 + x(1) - 2 + (x(2)-2).^2 + x(2);

Note!Theunknownsxandyisdefinedasavector,i.e., 𝑥, = 𝑥 1 = 𝑥, 𝑥> = 𝑥(2) = 𝑦.

𝑥 =𝑥,𝑥>

Ifthereismorethanonevariable,youhavetodoitthisway.

Thisgives:

x = 0.7500 1.5000 fval = 0.6250

→Theminimumisofthefunctionisgivenby 𝑥 = 0.75 and 𝑦 = 1.5.

Wecanalsoplotthefunction:

clear,clc [x,y] = meshgrid(-2:0.1:2, -1:0.1:3); f = 2.*(x-1).^2 + x - 2 + (y-2).^2 + y; figure(1) surf(x,y,f) figure(2) mesh(x,y,f) figure(3) surfl(x,y,f) shading interp; colormap(hot);

Forfigure3weget:

Page 45: MATLAB Course - Part II: Modelling, Simulation and Control

38 Optimization

MATLAB Course - Part II: Modelling, Simulation and Control

[EndofExample]

Task17: Optimization

Giventhefollowingfunction:

𝑓 𝑥 = 𝑥e − 4𝑥

→Plotthefunction

→Findtheminimumforthisfunction

[EndofTask]

Task18: Optimization-Rosenbrock'sBananaFunction

Giventhefollowingfunction:

𝑓 𝑥, 𝑦 = 1 − 𝑥 > + 100(𝑦 − 𝑥>)>

ThisfunctionisknownasRosenbrock'sbananafunction.

Thefunctionlookslikethis:

Page 46: MATLAB Course - Part II: Modelling, Simulation and Control

39 Optimization

MATLAB Course - Part II: Modelling, Simulation and Control

Theglobalminimumisinsidealong,narrow,parabolicshapedflatvalley.Tofindthevalleyistrivial.Toconvergetotheglobalminimum,however,isdifficult.ButMATLABwillhopefullydothejobforus.

Let’sseeifMATLABcandothejobforus.

→Plotthefunction

→Findtheminimumforthisfunction

[EndofTask]

Page 47: MATLAB Course - Part II: Modelling, Simulation and Control

40

6 ControlSystemToolboxThereareavailablelotsofadditionaltoolboxesforMATLAB.ToolboxesarespecializedcollectionsofM-filesbuiltforsolvingparticularclassesofproblems,e.g.,

• ControlSystemToolbox• SignalProcessingToolbox• StatisticsToolbox• SystemidentificationToolbox• etc.

Herewewilltakeacloserlookatthe“ControlSystemToolbox”.

ControlSystemToolboxbuildsonthefoundationsofMATLABtoprovidefunctionsdesignedforcontrolengineering.ControlSystemToolboxisacollectionofalgorithms,writtenmostlyasM-files,thatimplementscommoncontrolsystemdesign,analysis,andmodelingtechniques.Convenientgraphicaluserinterfaces(GUIs)simplifytypicalcontrolengineeringtasks.Controlsystemscanbemodeledastransferfunctions,inzero-pole-gainorstate-spaceform,allowingyoutousebothclassicalandmoderncontroltechniques.Youcanmanipulatebothcontinuous-timeanddiscrete-timesystems.Conversionsbetweenvariousmodel

Page 48: MATLAB Course - Part II: Modelling, Simulation and Control

41 ControlSystemToolbox

MATLAB Course - Part II: Modelling, Simulation and Control

representationsareprovided.Timeresponses,frequencyresponsescanbecomputedandgraphed.Otherfunctionsallowpoleplacement,optimalcontrol,andestimation.Finally,ControlSystemToolboxisopenandextensible.YoucancreatecustomM-filestosuityourparticularapplication.

Page 49: MATLAB Course - Part II: Modelling, Simulation and Control

42

7 TransferFunctionsItisassumedyouarefamiliarwithbasiccontroltheoryandtransferfunctions,ifnotyoumayskipthischapter.

7.1 IntroductionTransferfunctionsareamodelformbasedontheLaplacetransform.Transferfunctionsareveryusefulinanalysisanddesignoflineardynamicsystems.

Ageneraltransferfunctionisontheform:

𝐻 𝑆 =𝑦(𝑠)𝑢(𝑠)

Where 𝑦 istheoutputand 𝑢 istheinput.

FirstorderTransferFunction:

Afirstordertransferfunctionisgivenontheform:

𝐻 𝑠 =𝑦(𝑠)𝑢(𝑠) =

𝐾𝑇𝑠 + 1

there

𝐾 istheGain

𝑇 istheTimeconstant

A1.ordertransferfunctionwithtime-delayhasthefollowingcharacteristicstepresponse:

Page 50: MATLAB Course - Part II: Modelling, Simulation and Control

43 TransferFunctions

MATLAB Course - Part II: Modelling, Simulation and Control

Afirstordertransferfunctionwithtime-delayhasthefollowingtransferfunction:

𝐻 𝑠 =𝑦(𝑠)𝑢(𝑠) =

𝐾𝑇𝑠 + 1 𝑒

c}Z

Where 𝜏 isthetime-delay.

A1.ordertransferfunctionwithtime-delayhasthefollowingcharacteristicstepresponse:

MATLABhaveseveralfunctionsforcreatingandmanipulationoftransferfunctions:

Function Description Exampletf Createssystemmodelintransferfunctionform.Youalsocan

usethisfunctiontostate-spacemodelstotransferfunctionform.

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

pole Returnsthelocationsoftheclosed-looppolesofasystemmodel.

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

zero Findthezeros

Page 51: MATLAB Course - Part II: Modelling, Simulation and Control

44 TransferFunctions

MATLAB Course - Part II: Modelling, Simulation and Control

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)

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)

c2d Convertfromcontinuous-todiscrete-timemodels

d2c Convertfromdiscrete-tocontinuous-timemodels

Beforeyoustart,youshouldusetheHelpsysteminMATLABtoreadmoreaboutthesefunctions.Type“help<functionname>”intheCommandwindow.

Task19: Transferfunction

UsethetffunctioninMATLABtodefinethetransferfunctionabove.Set 𝐾 = 2 and 𝑇 = 3.

Type“help tf”intheCommandwindowtoseehowyouusethisfunction.

Example:

% Transfer function H=1/(s+1) num = [1]; den = [1, 1]; H = tf(num, den)

[EndofTask]

7.2 SecondorderTransferFunctionAsecondordertransferfunctionisgivenontheform:

𝐻 𝑠 =𝐾

𝑠𝜔'

>+ 2𝜁 𝑠

𝜔'+ 1

Where

𝐾 isthegain

Page 52: MATLAB Course - Part II: Modelling, Simulation and Control

45 TransferFunctions

MATLAB Course - Part II: Modelling, Simulation and Control

𝜁 zetaistherelativedampingfactor

𝜔'[rad/s]istheundampedresonancefrequency.

Task20: 2.orderTransferfunction

Definethetransferfunctionusingthetffunction.

Set 𝐾 = 1,𝜔' = 1

→Plotthestepresponse(usethestepfunctioninMATLAB)fordifferentvaluesof 𝜁.Select𝜁 asfollows:

𝜁 > 1

𝜁 = 1

0 < 𝜁 < 1

𝜁 = 0

𝜁 < 0

Tip!Fromcontroltheorywehavethefollowing:

Figure:F.Haugen,AdvancedDynamicsandControl:TechTeach,2010.

Page 53: MATLAB Course - Part II: Modelling, Simulation and Control

46 TransferFunctions

MATLAB Course - Part II: Modelling, Simulation and Control

Soyoushouldgetsimilarstepresponsesasshownabove.

[EndofTask]

Task21: TimeResponse

Giventhefollowingsystem:

𝐻 𝑠 =𝑠 + 1

𝑠> − 𝑠 + 3

Plotthetimeresponseforthetransferfunctionusingthestepfunction.Letthetime-intervalbefrom0to10seconds,e.g.,definethetimevectorlikethis:

t=[0:0.01:10]

andthenusethefunctionstep(H,t).

[EndofTask]

7.3 AnalysisofStandardFunctionsHerewewilltakeacloserlookatthefollowingstandardfunctions:

• Integrator• 1.Ordersystem• 2.Ordersystem

Task22: Integrator

ThetransferfunctionforanIntegratorisasfollows:

𝐻 𝑠 =𝐾𝑠

→Findthepole(s)

→PlottheStepresponse:Usedifferentvaluesfor 𝐾,e.g., 𝐾 = 0.2, 1, 5.UsethestepfunctioninMATLAB.

[EndofTask]

Task23: 1.ordersystem

Page 54: MATLAB Course - Part II: Modelling, Simulation and Control

47 TransferFunctions

MATLAB Course - Part II: Modelling, Simulation and Control

Thetransferfunctionfora1.ordersystemisasfollows:

𝐻 𝑠 =𝐾

𝑇𝑠 + 1

→Findthepole(s)

→PlottheStepresponse.UsethestepfunctioninMATLAB.

• Stepresponse1:Usedifferentvaluesfor 𝐾,e.g., 𝐾 = 0.5, 1, 2.Set 𝑇 = 1• Stepresponse2:Usedifferentvaluesfor 𝑇,e.g., 𝑇 = 0.2, 0.5, 1, 2, 4.Set 𝐾 = 1

[EndofTask]

Task24: 2.ordersystem

Thetransferfunctionfora2.ordersystemisasfollows:

𝐻 𝑠 =𝐾𝜔'>

𝑠> + 2𝜁𝜔'𝑠 + 𝜔'>=

𝐾𝑠𝜔'

>+ 2𝜁 𝑠

𝜔'+ 1

Where

• 𝐾 isthegain• 𝜁 zetaistherelativedampingfactor• 𝜔'[rad/s]istheundampedresonancefrequency.

→Findthepole(s)

→PlottheStepresponse:Usedifferentvaluesfor 𝜁,e.g., 𝜁 = 0.2, 1, 2.Set 𝜔' = 1 andK=1.UsethestepfunctioninMATLAB.

Tip!Fromcontroltheorywehavethefollowing:

Page 55: MATLAB Course - Part II: Modelling, Simulation and Control

48 TransferFunctions

MATLAB Course - Part II: Modelling, Simulation and Control

Figure:F.Haugen,AdvancedDynamicsandControl:TechTeach,2010.

Soyoushouldgetsimilarstepresponsesasshownabove.

[EndofTask]

Task25: 2.ordersystem–SpecialCase

Specialcase:When 𝜻 > 0 andthepolesarerealanddistinctwehave:

𝐻 𝑠 =𝐾

(𝑇,𝑠 + 1)(𝑇>𝑠 + 1)

Weseethatthissystemcanbeconsideredastwo1.ordersystemsinseries.

𝐻 𝑠 = 𝐻, 𝑠 𝐻, 𝑠 =𝐾

(𝑇,𝑠 + 1)∙

1(𝑇>𝑠 + 1)

=𝐾

(𝑇,𝑠 + 1)(𝑇>𝑠 + 1)

Page 56: MATLAB Course - Part II: Modelling, Simulation and Control

49 TransferFunctions

MATLAB Course - Part II: Modelling, Simulation and Control

Set 𝑇, = 2 and 𝑇> = 5

→Findthepole(s)

→PlottheStepresponse.SetK=1.Set 𝑇, = 1𝑎𝑛𝑑𝑇> = 0, 𝑇, = 1𝑎𝑛𝑑𝑇> = 0.05, 𝑇, =1𝑎𝑛𝑑𝑇> = 0.1, 𝑇, = 1𝑎𝑛𝑑𝑇> = 0.25,𝑇, = 1𝑎𝑛𝑑𝑇> = 0.5, 𝑇, = 1𝑎𝑛𝑑𝑇> = 1.UsethestepfunctioninMATLAB.

[EndofTask]

Page 57: MATLAB Course - Part II: Modelling, Simulation and Control

50

8 State-spaceModelsItisassumedyouarefamiliarwithbasiccontroltheoryandstate-spacemodels,ifnotyoumayskipthischapter.

8.1 IntroductionAstate-spacemodelisastructuredformorrepresentationofasetofdifferentialequations.State-spacemodelsareveryusefulinControltheoryanddesign.Thedifferentialequationsareconvertedinmatricesandvectors,whichisthebasicelementsinMATLAB.

Wehavethefollowingequations:

𝑥, = 𝑎,,𝑥, + 𝑎>,𝑥> + ⋯+ 𝑎b,𝑥b +𝑏,,𝑢, + 𝑏>,𝑢> + ⋯+ 𝑏b,𝑢b

𝑥b = 𝑎,�𝑥, + 𝑎>�𝑥> + ⋯+ 𝑎b�𝑥b +𝑏,�𝑢, + 𝑏>�𝑢> + ⋯+ 𝑏b,𝑢b

Thisgivesonvectorform:

𝑥,𝑥>⋮𝑥b0

=𝑎,, ⋯ 𝑎b,⋮ ⋱ ⋮

𝑎,� ⋯ 𝑎b��

𝑥,𝑥>⋮𝑥b0

+𝑏,, ⋯ 𝑏b,⋮ ⋱ ⋮𝑏,� ⋯ 𝑏b�

𝑢,𝑢>⋮𝑢b�

𝑦,𝑦>⋮𝑦bo

=𝑐,, ⋯ 𝑐b,⋮ ⋱ ⋮𝑐,� ⋯ 𝑐b�

𝑥,𝑥>⋮𝑥b0

+𝑑,, ⋯ 𝑑b,⋮ ⋱ ⋮

𝑑,� ⋯ 𝑑b��

𝑢,𝑢>⋮𝑢b�

ThisgivesthefollowingcompactformofagenerallinearState-spacemodel:

𝑥 = 𝐴𝑥 + 𝐵𝑢

𝑦 = 𝐶𝑥 + 𝐷𝑢

Page 58: MATLAB Course - Part II: Modelling, Simulation and Control

51 State-spaceModels

MATLAB Course - Part II: Modelling, Simulation and Control

Example:

Giventhefollowingequations:

𝑥, = −1𝐴1𝑥> +

1𝐴1𝐾�𝑢

𝑥> = 0

Theseequationscanbewrittenonthecompactstate-spaceform:

𝑥,𝑥>

= 0 −1𝐴1

0 0�

𝑥,𝑥> +

𝐾�𝐴10�

𝑢

𝑦 = 1 0�

𝑥,𝑥>

[EndofExample]

MATLABhaveseveralfunctionsforcreatingandmanipulationofState-spacemodels:

Function Description Exampless Constructsamodelinstate-spaceform.Youalsocanusethis

functiontoconverttransferfunctionmodelstostate-spaceform.

>A = [1 3; 4 6]; >B = [0; 1]; >C = [1, 0]; >D = 0; >sysOutSS = ss(A, B, C, D)

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)

c2d Convertfromcontinuous-todiscrete-timemodels

d2c Convertfromdiscrete-tocontinuous-timemodels

Example:

% Creates a state-space model A = [1 3; 4 6]; B = [0; 1]; C = [1, 0]; D = 0; SysOutSS = ss(A, B, C, D)

[EndofExample]

Page 59: MATLAB Course - Part II: Modelling, Simulation and Control

52 State-spaceModels

MATLAB Course - Part II: Modelling, Simulation and Control

Beforeyoustart,youshouldusetheHelpsysteminMATLABtoreadmoreaboutthesefunctions.Type“help<functionname>”intheCommandwindow.

8.2 Tasks

Task26: State-spacemodel

Implementthefollowingequationsasastate-spacemodelinMATLAB:

𝑥, = 𝑥>

2𝑥> = −2𝑥,−6𝑥>+4𝑢,+8𝑢>

𝑦 = 5𝑥,+6𝑥>+7𝑢,

→FindtheStepResponse

→Findthetransferfunctionfromthestate-spacemodelusingMATLABcode.

[EndofTask]

Task27: Mass-spring-dampersystem

Givenamass-spring-dampersystem:

Wherec=dampingconstant,m=mass,k=springconstant,F=u=force

Thestate-spacemodelforthesystemis:

𝑥,𝑥>

=0 1

−𝑘𝑚 −

𝑐𝑚

𝑥,𝑥> +

01𝑚

𝑢

Page 60: MATLAB Course - Part II: Modelling, Simulation and Control

53 State-spaceModels

MATLAB Course - Part II: Modelling, Simulation and Control

𝑦 = 1 0𝑥,𝑥>

Definethestate-spacemodelaboveusingthessfunctioninMATLAB.

Set 𝑐 = 1, 𝑚 = 1, 𝑘 = 50 (tryalsowithothervaluestoseewhathappens).

→ApplyastepinF(u)andusethestepfunctioninMATLABtosimulatetheresult.

→Findthetransferfunctionfromthestate-spacemodel

[EndofTask]

Task28: BlockDiagram

Findthestate-spacemodelfromtheblockdiagrambelowandimplementitinMATLAB.

Set

𝑎, = 5

𝑎> = 2

Andb=1,c=1

→SimulatethesystemusingthestepfunctioninMATLAB

[EndofTask]

Page 61: MATLAB Course - Part II: Modelling, Simulation and Control

54 State-spaceModels

MATLAB Course - Part II: Modelling, Simulation and Control

8.3 DiscreteState-spaceModelsForSimulationandControlincomputersdiscretesystemsareveryimportant.

Giventhecontinuouslinearstatespace-model:

𝑥 = 𝐴𝑥 + 𝐵𝑢

𝑦 = 𝐶𝑥 + 𝐷𝑢

Orgiventhediscretelinearstatespace-model

𝑥]^, = Φ𝑥] + Γ𝑢]

𝑦] = 𝐶𝑥] + 𝐷𝑢]

Oritisalsonormaltousethesamenotationfordiscretesystems:

𝑥]^, = 𝐴𝑥] + 𝐵𝑢]

𝑦] = 𝐶𝑥] + 𝐷𝑢]

Butthematrices 𝐴, 𝐵, 𝐶, 𝐷 isofcoursenotthesameasinthecontinuoussystem.

MATLABhasseveralfunctionsfordealingwithdiscretesystems:

Function Description Examplec2d Convertfromcontinuous-todiscrete-timemodels.Youmay

specifywhichDiscretizationmethodtouse>>c2d(sys,Ts) >>c2d(sys,Ts,‘tustin’)

d2c Convertfromdiscrete-tocontinuous-timemodels >>

Beforeyoustart,youshouldusetheHelpsysteminMATLABtoreadmoreaboutthesefunctions.Type“help<functionname>”intheCommandwindow.

Task29: Discretization

Thestate-spacemodelforthesystemis:

𝑥,𝑥>

=0 1

−𝑘𝑚 −

𝑐𝑚

𝑥,𝑥> +

01𝑚

𝑢

𝑦 = 1 0𝑥,𝑥>

Setsomearbitraryvaluesfor 𝑘, 𝑐 and 𝑚.

Page 62: MATLAB Course - Part II: Modelling, Simulation and Control

55 State-spaceModels

MATLAB Course - Part II: Modelling, Simulation and Control

FindthediscreteState-spacemodelusingMATLAB.

[EndofTask]

Page 63: MATLAB Course - Part II: Modelling, Simulation and Control

56

9 FrequencyResponseInthischapterweassumethatyouarefamiliarwithbasiccontroltheoryandfrequencyresponsefrompreviouscoursesincontroltheory/processcontrol/cybernetics.Ifnot,youmayskipthischapter.

9.1 IntroductionThefrequencyresponseofasystemisafrequencydependentfunctionwhichexpresseshowasinusoidalsignalofagivenfrequencyonthesysteminputistransferredthroughthesystem.Eachfrequencycomponentisasinusoidalsignalhavingacertainamplitudeandacertainfrequency.

Thefrequencyresponseisanimportanttoolforanalysisanddesignofsignalfiltersandforanalysisanddesignofcontrolsystems.Thefrequencyresponsecanbefoundexperimentallyorfromatransferfunctionmodel.

WecanfindthefrequencyresponseofasystembyexcitingthesystemwithasinusoidalsignalofamplitudeAandfrequencyω[rad/s](Note: 𝜔 = 2𝜋𝑓)andobservingtheresponseintheoutputvariableofthesystem.

Thefrequencyresponseofasystemisdefinedasthesteady-stateresponseofthesystemtoasinusoidalinputsignal.Whenthesystemisinsteady-stateitdiffersfromtheinputsignalonlyinamplitude/gain(A)andphaselag(𝜙).

Ifwehavetheinputsignal:

𝑢 𝑡 = 𝑈𝑠𝑖𝑛𝜔𝑡

Thesteady-stateoutputsignalwillbe:

𝑦 𝑡 = 𝑈𝐴�sin(𝜔𝑡 + 𝜙)

Where 𝐴 = ��

is theratiobetweentheamplitudesoftheoutputsignalandtheinputsignal

(insteady-state).

Aand 𝜙 isafunctionofthefrequencyωsowemaywrite 𝐴 = 𝐴 𝜔 ,𝜙 = 𝜙(𝜔)

Page 64: MATLAB Course - Part II: Modelling, Simulation and Control

57 FrequencyResponse

MATLAB Course - Part II: Modelling, Simulation and Control

Foratransferfunction

𝐻 𝑆 =𝑦(𝑠)𝑢(𝑠)

Wehavethat:

𝐻 𝑗𝜔 = 𝐻(𝑗𝜔) 𝑒 ∠¢( £)

Where 𝐻(𝑗𝜔) isthefrequencyresponseofthesystem,i.e.,wemayfindthefrequencyresponsebysetting 𝑠 = 𝑗𝜔 inthetransferfunction.Bodediagramsareusefulinfrequencyresponseanalysis.TheBodediagramconsistsof2diagrams,theBodemagnitudediagram,𝐴(𝜔) andtheBodephasediagram, 𝜙(𝜔).

TheGainfunction:

𝐴 𝜔 = 𝐻(𝑗𝜔)

ThePhasefunction:

𝜙 𝜔 = ∠𝐻(𝑗𝜔)

The 𝐴(𝜔)-axisisindecibel(dB),wherethedecibelvalueofxiscalculatedas: 𝒙 𝒅𝑩 =𝟐𝟎𝒍𝒐𝒈𝟏𝟎𝒙

The 𝜙(𝜔)-axisisindegrees(notradians!)

MATLABhaveseveralfunctionsforfrequencyresponse:

Function Description Examplebode CreatestheBodemagnitudeandBodephaseplotsofasystem

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

Example:

HereyouwilllearntoplotthefrequencyresponseinaBodediagram.

Page 65: MATLAB Course - Part II: Modelling, Simulation and Control

58 FrequencyResponse

MATLAB Course - Part II: Modelling, Simulation and Control

Wehavethefollowingtransferfunction

𝐻 𝑠 =𝑦(𝑠)𝑢(𝑠) =

1𝑠 + 1

BelowweseethescriptforcreatingthefrequencyresponseofthesysteminabodeplotusingthebodefunctioninMATLAB.Usethegridfunctiontoapplyagridtotheplot.

% Transfer function H=1/(s+1) num=[1]; den=[1, 1]; H = tf(num, den) bode (H);

TheBodeplot:

[EndofExample]

Beforeyoustart,youshouldusetheHelpsysteminMATLABtoreadmoreaboutthesefunctions.Type“help<functionname>”intheCommandwindow.

Page 66: MATLAB Course - Part II: Modelling, Simulation and Control

59 FrequencyResponse

MATLAB Course - Part II: Modelling, Simulation and Control

9.2 Tasks

Task30: 1.ordersystem

Wehavethefollowingtransferfunction:

𝐻 𝑠 =4

2𝑠 + 1

→Whatisthebreakfrequency?

→Setupthemathematicalexpressionsfor 𝐴(𝜔) and 𝜙(𝜔).Use“Pen&Paper”forthisAssignment.

→PlotthefrequencyresponseofthesysteminabodeplotusingthebodefunctioninMATLAB.Discusstheresults.

→Find 𝐴(𝜔) and 𝜙(𝜔) forthefollowingfrequenciesusingMATLABcode(usethebodefunction):

𝝎 𝑨 𝝎 [𝒅𝑩] 𝝓 𝝎 (𝒅𝒆𝒈𝒓𝒆𝒆𝒔) 0.1 0.16 0.25 0.4 0.625 2.5

Makesure 𝐴 𝜔 isindB.

→Find 𝐴(𝜔) and 𝜙(𝜔) forthesamefrequenciesaboveusingthemathematicalexpressionsfor 𝐴(𝜔) and 𝜙(𝜔).Tip:UseaForLoopordefineavectorw=[0.1,0.16,0.25,0.4,0.625,2.5].

[EndofTask]

Task31: BodeDiagram

Wehavethefollowingtransferfunction:

𝐻 𝑆 =(5𝑠 + 1)

2𝑠 + 1 (10𝑠 + 1)

→Whatisthebreakfrequencies?

Page 67: MATLAB Course - Part II: Modelling, Simulation and Control

60 FrequencyResponse

MATLAB Course - Part II: Modelling, Simulation and Control

→Setupthemathematicalexpressionsfor 𝐴(𝜔) and 𝜙(𝜔).Use“Pen&Paper”forthisAssignment.

→PlotthefrequencyresponseofthesysteminabodeplotusingthebodefunctioninMATLAB.Discusstheresults.

→Find 𝐴(𝜔) and 𝜙(𝜔) forsomegivenfrequenciesusingMATLABcode(usethebodefunction).

→Find 𝐴(𝜔) and 𝜙(𝜔) forthesamefrequenciesaboveusingthemathematicalexpressionsfor 𝐴(𝜔) and 𝜙(𝜔).Tip:useaForLoopordefineavectorw=[0.01,0.1,…].

[EndofTask]

9.3 FrequencyresponseAnalysisHerearesomeimportanttransferfunctionstodeterminethestabilityofafeedbacksystem.Belowweseeatypicalfeedbacksystem.

9.3.1 LoopTransferFunction

TheLooptransferfunction 𝑳(𝒔) isdefinedasfollows:

𝐿 𝑠 = 𝐻±𝐻�𝐻�

Where

𝐻± istheControllertransferfunction

𝐻� istheProcesstransferfunction

𝐻� istheMeasurement(sensor)transferfunction

Note!Anothernotationfor 𝐿 is 𝐻'

Page 68: MATLAB Course - Part II: Modelling, Simulation and Control

61 FrequencyResponse

MATLAB Course - Part II: Modelling, Simulation and Control

9.3.2 TrackingTransferFunction

TheTrackingtransferfunction 𝑻(𝒔) isdefinedasfollows:

𝑇 𝑠 =𝑦(𝑠)𝑟(𝑠) =

𝐻±𝐻�𝐻�1 + 𝐻±𝐻�𝐻�

=𝐿(𝑠)

1 + 𝐿(𝑠) = 1 − 𝑆(𝑠)

TheTrackingPropertyisgoodifthetrackingfunctionThasvalueequaltoorcloseto1:

𝑇 ≈ 1

9.3.3 SensitivityTransferFunction

TheSensitivitytransferfunction 𝑺(𝒔) isdefinedasfollows:

𝑆 𝑠 =𝑒(𝑠)𝑟(𝑠) =

11 + 𝐿(𝑠) = 1 − 𝑇(𝑠)

TheCompensationPropertyisgoodifthesensitivityfunctionShasasmallvalueclosetozero:

𝑆 ≈ 0𝑜𝑟 𝑆 ≪ 1

Note!

𝑇 𝑠 + 𝑆 𝑠 =𝐿(𝑠)

1 + 𝐿(𝑠) +1

1 + 𝐿(𝑠) ≡ 1

FrequencyResponseAnalysisoftheTrackingProperty:

Fromtheequationsabovewefind:

TheTrackingPropertyisgoodif:

𝐿(𝑗𝜔) ≫ 1

TheTrackingPropertyispoorif:

𝐿(𝑗𝜔) ≪ 1

IfweplotL,TandSinaBodeplotwegetaplotlikethis:

Page 69: MATLAB Course - Part II: Modelling, Simulation and Control

62 FrequencyResponse

MATLAB Course - Part II: Modelling, Simulation and Control

WherethefollowingBandwidths 𝜔1, 𝜔±, 𝜔Z aredefined:

𝝎𝒄 –crossover-frequency–thefrequencywherethegainoftheLooptransferfunction𝐿(𝑗𝜔) hasthevalue:

1 = 0𝑑𝐵

𝝎𝒕 –thefrequencywherethegainoftheTrackingfunction 𝑇(𝑗𝜔) hasthevalue:

12≈ 0.71 = −3𝑑𝐵

𝝎𝒔 -thefrequencywherethegainoftheSensitivitytransferfunction 𝑆(𝑗𝜔) hasthevalue:

1 −12≈ 0.29 = −11𝑑𝐵

Task32: FrequencyResponseAnalysis

Giventhefollowingsystem:

Processtransferfunction:

𝐻� =𝐾𝑠

Where 𝐾 = º»¼�,where 𝐾Z = 0,556, 𝐴 = 13,4, 𝜚 = 145

Page 70: MATLAB Course - Part II: Modelling, Simulation and Control

63 FrequencyResponse

MATLAB Course - Part II: Modelling, Simulation and Control

Measurement(sensor)transferfunction:

𝐻� = 𝐾�

Where 𝐾� = 1.

Controllertransferfunction(PIController):

𝐻± = 𝐾� +𝐾�𝑇v𝑠

SetKp=1,5ogTi=1000sec.

→DefinetheLooptransferfunction 𝑳(𝒔),Sensitivitytransferfunction 𝑺(𝒔) andTrackingtransferfunction 𝑻(𝒔) andinMATLAB.

→PlottheLooptransferfunction 𝐿(𝑠),theTrackingtransferfunction 𝑇(𝑠) andtheSensitivitytransferfunction 𝑆(𝑠) inthesameBodediagram.Use,e.g.,thebodemagfunctioninMATLAB.

→Findthebandwidths 𝜔1, 𝜔±, 𝜔Z fromtheplotabove.

→PlotthestepresponsefortheTrackingtransferfunction 𝑇(𝑠)

[EndofTask]

9.4 StabilityAnalysisofFeedbackSystemsGainMargin(GM)andPhaseMargin(PM)areimportantdesigncriteriaforanalysisoffeedbackcontrolsystems.

Adynamicsystemhasoneofthefollowingstabilityproperties:

• Asymptoticallystablesystem• Marginallystablesystem• Unstablesystem

TheGainMargin–GM(Δ𝐾)ishowmuchtheloopgaincanincreasebeforethesystembecomeunstable.

Page 71: MATLAB Course - Part II: Modelling, Simulation and Control

64 FrequencyResponse

MATLAB Course - Part II: Modelling, Simulation and Control

ThePhaseMargin-PM(𝜑)ishowmuchthephaselagfunctionoftheloopcanbereducedbeforetheloopbecomesunstable.

Where:

• 𝝎𝟏𝟖𝟎(gainmarginfrequency-gmf)isthegainmarginfrequency/frequencies,inradians/second.Againmarginfrequencyindicateswherethemodelphasecrosses-180degrees.

• GM(Δ𝐾)isthegainmargin(s)ofthesystem. • 𝝎𝒄 (phasemarginfrequency-pmf)returnsthephasemarginfrequency/frequencies,

inradians/second.Aphasemarginfrequencyindicateswherethemodelmagnitudecrosses0decibels.

• PM(𝜑)isthephasemargin(s)ofthesystem.

Note! 𝝎𝟏𝟖𝟎 and 𝝎𝒄arecalledthecrossover-frequencies

Thedefinitionsareasfollows:

GainCrossover-frequency- 𝝎𝒄:

𝐿 𝑗𝜔± = 1 = 0𝑑𝐵

PhaseCrossover-frequency- 𝝎𝟏𝟖𝟎:

∠𝐿 𝑗𝜔,Á' = −180Â

GainMargin-GM(𝚫𝑲):

𝐺𝑀 = ,Ç  £ÈÉÊ

Page 72: MATLAB Course - Part II: Modelling, Simulation and Control

65 FrequencyResponse

MATLAB Course - Part II: Modelling, Simulation and Control

or:

𝐺𝑀 𝑑𝐵 = − 𝐿 𝑗𝜔,Á' 𝑑𝐵

PhasemarginPM(𝝋):

𝑃𝑀 = 180Â + ∠𝐿(𝑗𝜔±)

Wehavethat:

• Asymptoticallystablesystem: 𝝎𝒄 < 𝝎𝟏𝟖𝟎• Marginallystablesystem: 𝝎𝒄 = 𝝎𝟏𝟖𝟎• Unstablesystem: 𝝎𝒄 > 𝝎𝟏𝟖𝟎

WeusethefollowingfunctionsinMATLAB:tf,bode,marginsandmargin.

Task33: StabilityAnalysis

Giventhefollowingsystem:

𝐻 𝑆 =1

𝑠 𝑠 + 1 >

Wewillfindthecrossover-frequenciesforthesystemusingMATLAB.Wewillalsofindalsothegainmarginsandphasemarginsforthesystem.

Plotabodediagramwherethecrossover-frequencies,GMandPMareillustrated.Tip!UsethemarginfunctioninMATLAB.

[EndofTask]

Page 73: MATLAB Course - Part II: Modelling, Simulation and Control

66

10 AdditionalTasksIfyouhavetimeleftorneedmorepractice,solvethetasksbelow.

Task34: ODESolvers

Usetheode45functiontosolveandplottheresultsofthefollowingdifferentialequationintheinterval [𝑡', 𝑡L]:

𝟑𝒘( +𝟏

𝟏 + 𝒕𝟐 𝒘 = 𝒄𝒐𝒔𝒕, 𝑡' = 0, 𝑡L = 5,𝑤 𝑡' = 1

[EndofTask]

Task35: Mass-spring-dampersystem

Givenamass-spring-dampersystem:

Wherec=dampingconstant,m=mass,k=springconstant,F=u=force

Thestate-spacemodelforthesystemis:

𝑥,𝑥>

=0 1

−𝑘𝑚 −

𝑐𝑚

𝑥,𝑥> +

01𝑚

𝑢

Set 𝑐 = 1,𝑚 = 1, 𝑘 = 50.

→SolveandPlotthesystemusingoneormoreofthebuilt-insolvers(use,e.g.,ode32)inMATLAB.Applyastepin 𝐹 (whichisthecontrolsignal 𝑢).

Page 74: MATLAB Course - Part II: Modelling, Simulation and Control

67 AdditionalTasks

MATLAB Course - Part II: Modelling, Simulation and Control

[EndofTask]

Task36: NumericalIntegration

Givenapistoncylinderdevice:

→Findtheworkproducedinapistoncylinderdevicebysolvingtheequation:

𝑊 = 𝑃𝑑𝑉ÐY

ÐÈ

Assumetheidealgaslowapplies:

𝑃𝑉 = 𝑛𝑅𝑇

where

• P=pressure• V=volume,m3 • n=numberofmoles,kmol• R=universalgasconstant,8.314kJ/kmolK• T=Temperature,K

Wealsoassumethatthepistoncontains1molofgasat300Kandthatthetemperatureisconstantduringtheprocess. 𝑉, = 1𝑚e, 𝑉> = 5𝑚e

Useboththequadandquadlfunctions.Comparewiththeexactsolutionbysolvingtheintegralanalytically.

[EndofTask]

Page 75: MATLAB Course - Part II: Modelling, Simulation and Control

68 AdditionalTasks

MATLAB Course - Part II: Modelling, Simulation and Control

Task37: State-spacemodel

Thefollowingmodelofapendulumisgiven:

𝑥, = 𝑥>

𝑥> = −𝑔𝑟 𝑥, −

𝑏𝑚𝑟> 𝑥>

wheremisthemass,risthelengthofthearmofthependulum,gisthegravity,bisafrictioncoefficient.

→Definethestate-spacemodelinMATLAB

→SolvethedifferentialequationsinMATLABandplottheresults.

Usethefollowingvalues 𝑔 = 9.81,𝑚 = 8, 𝑟 = 5, 𝑏 = 10

[EndofTask]

Task38: lsim

Givenamass-spring-dampersystem:

Wherec=dampingconstant,m=mass,k=springconstant,F=u=force

Thestate-spacemodelforthesystemis:

𝑥,𝑥>

=0 1

−𝑘𝑚 −

𝑐𝑚

𝑥,𝑥> +

01𝑚

𝑢

𝑦 = 1 0𝑥,𝑥>

→SimulatethesystemusingthelsimfunctionintheControlSystemToolbox.

Page 76: MATLAB Course - Part II: Modelling, Simulation and Control

69 AdditionalTasks

MATLAB Course - Part II: Modelling, Simulation and Control

Setc=1,m=1,k=50.

[EndofTask]

Page 77: MATLAB Course - Part II: Modelling, Simulation and Control

70

AppendixA–MATLABFunctions

NumericalTechniquesHerearesomedescriptionsforthemostusedMATLABfunctionsforNumericalTechniques.

SolvingOrdinaryDifferentialEquations

MATLABofferslotsofodesolvers,e.g.:

Function Description Exampleode23

ode45

Interpolation

MATLABoffersfunctionsforinterpolation,e.g.:

Function Description Exampleinterp1

CurveFitting

HerearesomeofthefunctionsavailableinMATLABusedforcurvefitting:

Function Description Examplepolyfit P=POLYFIT(X,Y,N)findsthecoefficientsofapolynomialP(X)of

degreeNthatfitsthedataYbestinaleast-squaressense.Pisa rowvectoroflengthN+1containingthepolynomialcoefficientsindescendingpowers,P(1)*X^N+P(2)*X^(N-1)+...+P(N)*X+P(N+1).

>>polyfit(x,y,1)

polyval Evaluatepolynomial.Y=POLYVAL(P,X)returnsthevalueofapolynomialPevaluatedatX.PisavectoroflengthN+1whoseelementsarethecoefficientsofthepolynomialindescendingpowers.Y=P(1)*X^N+P(2)*X^(N-1)+...+P(N)*X+P(N+1)

Page 78: MATLAB Course - Part II: Modelling, Simulation and Control

71 AppendixA–MATLABFunctions

MATLAB Course - Part II: Modelling, Simulation and Control

NumericalDifferentiation

MATLABoffersfunctionsfornumericaldifferentiation,e.g.:

Function Description Examplediff Differenceandapproximatederivative.DIFF(X),foravectorX,

is[X(2)-X(1) X(3)-X(2)...X(n)-X(n-1)].>> dydx_num=diff(y)./diff(x);

polyder Differentiatepolynomial.POLYDER(P)returnsthederivativeofthepolynomialwhosecoefficientsaretheelementsofvectorP.POLYDER(A,B)returnsthederivativeofpolynomialA*B.

>>p=[1,2,3]; >>polyder(p)

NumericalIntegration

MATLABoffersfunctionsfornumericalintegration,suchas:

Function Description Examplediff Differenceandapproximatederivative.DIFF(X),foravectorX,

is[X(2)-X(1) X(3)-X(2)...X(n)-X(n-1)].>> dydx_num=diff(y)./diff(x);

quad Numericallyevaluateintegral,adaptiveSimpsonquadrature.Q=QUAD(FUN,A,B)triestoapproximatetheintegralofcalar-valuedfunctionFUNfromAtoB.FUNisafunctionhandle.ThefunctionY=FUN(X)shouldacceptavectorargumentXandreturnavectorresultY,theintegrandevaluatedateachelementofX.UsesadaptiveSimpsonquadraturemethod

>>

quadl Sameasquad,butusesadaptiveLobattoquadraturemethod >>

polyint Integratepolynomialanalytically. POLYINT(P,K)returnsapolynomialrepresentingtheintegralofpolynomialP,usingascalarconstantofintegrationK.

OptimizationMATLABoffersfunctionsforlocalminimum,suchas:

Function Description Examplefminbnd X=FMINBND(FUN,x1,x2)attemptstofindalocalminimizer

XofthefunctionFUNintheintervalx1<X<x2.FUNisafunctionhandle. FUNacceptsscalarinputXandreturnsascalarfunctionvalueFevaluatedatX.FUNcanbespecifiedusing@.FMINBNDisasingle-variableboundednonlinearfunctionminimization.

>> x = fminbnd(@cos,3,4) x = 3.1416

fminsearch X=FMINSEARCH(FUN,X0)startsatX0andattemptstofindalocalminimizerXofthefunctionFUN.FUNisafunctionhandle. FUNacceptsinputXandreturnsascalarfunctionvalueFevaluatedatX.X0canbeascalar,vectorormatrix.FUNcanbespecifiedusing@.FMINSEARCHisamultidimensionalunconstrainednonlinearfunctionminimization.

>> x = fminsearch(@sin,3) x = 4.7124

Page 79: MATLAB Course - Part II: Modelling, Simulation and Control

72 AppendixA–MATLABFunctions

MATLAB Course - Part II: Modelling, Simulation and Control

ControlandSimulationHerearesomedescriptionsforthemostusedMATLABfunctionsforControlandSimulation.

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)

pole Returnsthelocationsoftheclosed-looppolesofasystemmodel.

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

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)

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)

ss Constructsamodelinstate-spaceform.Youalsocanusethisfunctiontoconverttransferfunctionmodelstostate-spaceform.

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

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)

c2d Convertfromcontinuous-todiscrete-timemodels

d2c Convertfromdiscrete-tocontinuous-timemodels

Page 80: MATLAB Course - Part II: Modelling, Simulation and Control

Hans-PetterHalvorsen,M.Sc.

E-mail:[email protected]

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

UniversityCollegeofSoutheastNorway

www.usn.no