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

MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

Mar 19, 2018

Download

Documents

phamdiep
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 Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

UniversityCollegeofSoutheastNorway

MATLAB PartII:Modelling,Simulation&Control

Hans-PetterHalvorsen,2016.06.22

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

Page 2: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

MATLABCourse,PartII-Solutions

TableofContents1 Introduction......................................................................................................................4

2 DifferentialEquationsandODESolvers............................................................................5

Task1: BacteriaPopulation.......................................................................................5

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

Task3: ODESolvers...................................................................................................7

Task4: 2.orderdifferentialequation.........................................................................9

3 DiscreteSystems.............................................................................................................12

Task5: DiscreteSimulation.....................................................................................12

Task6: DiscreteSimulation–BacteriaPopulation..................................................14

Task7: Simulationwith2variables.........................................................................15

4 NumericalTechniques.....................................................................................................18

Task8: Interpolation................................................................................................18

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

Task10: PolynomialRegression.............................................................................21

Task11: Modelfitting............................................................................................22

Task12: NumericalDifferentiation........................................................................25

Task13: DifferentiationonPolynomials................................................................28

Task14: DifferentiationonPolynomials................................................................29

Task15: NumericalIntegration.............................................................................30

Task16: IntegrationonPolynomials.....................................................................32

5 Optimization....................................................................................................................34

Task17: Optimization............................................................................................34

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

Page 3: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

MATLABCourse,PartII-Solutions

6 ControlSystemToolbox..................................................................................................38

7 TransferFunctions...........................................................................................................39

Task19: Transferfunction.....................................................................................39

Task20: 2.orderTransferfunction.......................................................................40

Task21: TimeResponse........................................................................................43

Task22: Integrator................................................................................................44

Task23: 1.ordersystem........................................................................................48

Task24: 2.ordersystem........................................................................................53

Task25: 2.ordersystem–SpecialCase................................................................56

8 State-SpaceModels.........................................................................................................59

Task26: State-spacemodel...................................................................................59

Task27: Mass-spring-dampersystem...................................................................61

Task28: BlockDiagram..........................................................................................63

Task29: Discretization...........................................................................................64

9 FrequencyResponse.......................................................................................................66

Task30: 1.ordersystem........................................................................................66

Task31: BodeDiagram..........................................................................................71

Task32: FrequencyResponseAnalysis..................................................................73

Task33: StabilityAnalysis......................................................................................78

10 AdditionalTasks..........................................................................................................82

Task34: ODESolvers.............................................................................................82

Task35: Mass-spring-dampersystem...................................................................83

Task36: NumericalIntegration.............................................................................85

Task37: State-spacemodel...................................................................................87

Task38: lsim..........................................................................................................89

Page 4: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

4

1 IntroductionNoTasks

Page 5: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

5

2 DifferentialEquationsandODESolvers

Task1: BacteriaPopulation

Inthistaskwewillsimulateasimplemodelofabacteriapopulationinajar.

Themodelisasfollows:

birthrate=bx

deathrate=px2

Thenthetotalrateofchangeofbacteriapopulationis:

𝑥 = 𝑏𝑥 − 𝑝𝑥2

Setb=1/hourandp=0.5bacteria-hour

→Simulatethenumberofbacteriainthejarafter1hour,assumingthatinitiallythereare100bacteriapresent.

[EndofTask]

Solution:

Wedefinethefunctionforthedifferentialequation:

function dx = bacteriadiff(t,x) % My Simple Differential Equation b=1; p=0.5; dx = b*x - p*x^2;

Wecreateascripttosolvethedifferentialequationusingaodefunction:

tspan=[0 1]; x0=100;

Page 6: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

6 DifferentialEquationsandODESolvers

MATLABCourse,PartII-Solutions

[t,y]=ode45(@bacteriadiff, tspan,x0); plot(t,y)

Theresultbecomes:

Task2: PassingParameterstothemodel

Giventhefollowingsystem:

𝑥 = 𝑎𝑥 + 𝑏

where 𝑎 = − 56 ,where 𝑇 isthetimeconstant

Inthiscasewewanttopassaandbasparameters,tomakeiteasytobeabletochangevaluesfortheseparameters

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

Thefunctionforthedifferentialequationis:

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

Page 7: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

7 DifferentialEquationsandODESolvers

MATLABCourse,PartII-Solutions

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,itisveryeasytochangesvaluesfortheparametersaandb.

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

Theresultfromthesimulationis:

→Writethecodeabove

ReadmoreaboutthedifferentsolversthatexistsintheHelpsysteminMATLAB

[EndofTask]

Task3: ODESolvers

Page 8: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

8 DifferentialEquationsandODESolvers

MATLABCourse,PartII-Solutions

Usetheode23functiontosolveandplottheresultsofthefollowingdifferentialequationintheinterval [𝑡?, 𝑡A]:

𝒘D + 𝟏. 𝟐 + 𝒔𝒊𝒏𝟏𝟎𝒕 𝒘 = 𝟎, 𝑡? = 0, 𝑡A = 5,𝑤 𝑡? = 1

[EndofTask]

Solution:

Westartbyrewritingthedifferentialequation:

𝑤D = − 1.2 + 𝑠𝑖𝑛10𝑡 𝑤

Thisgives:

function dw = diff_task3(t,w) dw = -(1.2 + sin(10*t))*w;

TheScriptforsolvingtheequation:

tspan=[0 5]; w0=1; [t,w]=ode23(@diff_task3, tspan, w0); plot(t,w)

Thisgives:

Page 9: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

9 DifferentialEquationsandODESolvers

MATLABCourse,PartII-Solutions

Task4: 2.orderdifferentialequation

Usetheode23/ode45functiontosolveandplottheresultsofthefollowingdifferentialequationintheinterval [𝑡?, 𝑡A]:

𝟏 + 𝒕𝟐 𝒘 + 𝟐𝒕𝒘 + 𝟑𝒘 = 𝟐, 𝑡? = 0, 𝑡A = 5,𝑤 𝑡? = 0,𝑤 𝑡? = 1

Note!Higherorderdifferentialequationsmustbereformulatedintoasystemoffirstorderdifferentialequations.

Tip1:Reformulatethedifferentialequationso 𝑤 isaloneontheleftside.

Tip2:Set:

𝑤 = 𝑥5

𝑤 = 𝑥2

[EndofTask]

Solution:

Firstwerewritelikethis:

𝑤 =2 − 2𝑡𝑤 − 3𝑤

1 + 𝑡2

InordertosolveitusingtheodefunctionsinMATLABithastobeasetwith1.orderode’s.

Soweset:

𝑤 = 𝑥5

𝑤 = 𝑥2

Thisgives:

𝑥5 = 𝑥2

𝑥2 =2 − 2𝑡𝑥2 − 3𝑥5

1 + 𝑡2

NowwecanuseMATLABtosolvetheequations:

function dx = diff_secondorder(t,x) [m,n] = size(x); dx = zeros(m,n)

Page 10: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

10 DifferentialEquationsandODESolvers

MATLABCourse,PartII-Solutions

dx(1) = x(2); dx(2) = (2-2*t*x(2)-3*x(1))/(1+t^2);

and:

tspan=[0 5]; x0=[0; 1]; [t,x]=ode23(@diff_secondorder, tspan, x0); plot(t,x) legend('x1','x2')

Thisgives:

ifwewanttoplotonly 𝑤 = 𝑥5 wecanuse

plot(t,x(:,1))

Likethis:

tspan=[0 5]; x0=[0; 1]; [t,x]=ode23(@diff_secondorder, tspan, x0); plot(t, x(:,2))

Thisgives:

Page 11: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

11 DifferentialEquationsandODESolvers

MATLABCourse,PartII-Solutions

Sothesolutionto:

𝟏 + 𝒕𝟐 𝒘 + 𝟐𝒕𝒘 + 𝟑𝒘 = 𝟐, 𝑡? = 0, 𝑡A = 5,𝑤 𝑡? = 0,𝑤 𝑡? = 1

istheplotabove.

Page 12: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

12

3 DiscreteSystemsTask5: DiscreteSimulation

Giventhefollowingdifferentialequation:

𝑥 = 𝑎𝑥

where 𝑎 = − 56 ,where 𝑇 isthetimeconstant

Note! 𝑥 = STSU

FindthediscretedifferentialequationandplotthesolutionforthissystemusingMATLAB.

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

CreateascriptinMATLAB(.mfile)whereweplotthesolution 𝑥(𝑘).

[EndofTask]

Solution:

Wecanusee.g.,theEulerApproximation:

𝑥 ≈𝑥XY5 − 𝑥X

𝑇Z

Thenweget:

𝑥XY5 − 𝑥X𝑇Z

= 𝑎𝑥X

Whichgives:

𝑥XY5 = 𝑥X(1 + 𝑇Z𝑎)

MATLABCode:

% Simulation of discrete model clear, clc % Model Parameters T = 5;

Page 13: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

13 DiscreteSystems

MATLABCourse,PartII-Solutions

a = -1/T; % Simulation Parameters Ts = 0.1; %s Tstop = 30; %s x(1) = 1; % Simulation for k=1:(Tstop/Ts) x(k+1) = (1+a*Ts).*x(k); end % Plot the Simulation Results k=0:Ts:Tstop; plot(k,x) grid on

Plot:

Page 14: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

14 DiscreteSystems

MATLABCourse,PartII-Solutions

Task6: DiscreteSimulation–BacteriaPopulation

Inthistaskwewillsimulateasimplemodelofabacteriapopulationinajar.

Themodelisasfollows:

birthrate=bx

deathrate=px2

Thenthetotalrateofchangeofbacteriapopulationis:

𝑥 = 𝑏𝑥 − 𝑝𝑥2

Setb=1/hourandp=0.5bacteria-hour

Wewillsimulatethenumberofbacteriainthejarafter1hour,assumingthatinitiallythereare100bacteriapresent.

→FindthediscretemodelusingtheEulerForwardmethodbyhandandimplementandsimulatethesysteminMATLABusingaForLoop.

[EndofTask]

Solution:

Wecreateadiscretemodel.anduseEulerForwarddifferentiationmethod:

𝑥 ≈𝑥XY5 − 𝑥X

𝑇Z

Where 𝑇Z istheSamplingTime.

Weget:

𝑥XY5 − 𝑥X𝑇Z

= 𝑏𝑥X − 𝑝𝑥X2

Thisgives:

𝑥XY5 = 𝑥X + 𝑇Z(𝑏𝑥X − 𝑝𝑥X2)

WeimplementthemodelinMATLAB:

clc % Model Parameters b = 1;

Page 15: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

15 DiscreteSystems

MATLABCourse,PartII-Solutions

p = 0.5; % Simulation Parameters Ts=0.01; x(1)=100; k=1; % Simulation Loop for i=Ts:Ts:1 % Discrete model x(k+1) = x(k) + Ts*(b.*x(k) - p*x(k).^2); k=k+1; end % Plot the simulation results i = 0:Ts:1; plot(x, i)

Thesimulationresultbecomes:

Task7: Simulationwith2variables

Giventhefollowingsystem

𝑑𝑥5𝑑𝑡 = −𝑥2

𝑑𝑥2𝑑𝑡 = 𝑥5

Page 16: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

16 DiscreteSystems

MATLABCourse,PartII-Solutions

FindthediscretesystemandsimulatethediscretesysteminMATLAB.

[EndofTask]

Solution:

UsingEulergives:

𝑥5 𝑘 + 1 = 𝑥5 𝑘 − 𝑇Z𝑥2 𝑘

𝑥2 𝑘 + 1 = 𝑥2 𝑘 + 𝑇Z𝑥5 𝑘

MATLABCode:

% Simulation of discrete model clear, clc % Model Parameters T = 5; a = -1/T; % Simulation Parameters Ts = 0.1; %s Tstop = 10; %s x1(1) = 1; x2(1) = 1; % Simulation for k=1:(Tstop/Ts) x1(k+1) = x1(k) - Ts.*x2(k); x2(k+1) = x2(k) + Ts.*x1(k); end % Plot the Simulation Results k=0:Ts:Tstop; plot(k,x1,k,x2) grid on

Plot:

Page 17: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

17 DiscreteSystems

MATLABCourse,PartII-Solutions

Page 18: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

18

4 NumericalTechniquesTask8: 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.

Whatistheinterpolatedvalueforu=2680.78KJ/kg?

[EndofTask]

Solution:

MATLABScript:

T = [100, 150, 200, 250, 300, 400, 500]; u=[2506.7, 2582.8, 2658.1, 2733.7, 2810.4, 2967.9, 3131.6]; figure(1) plot(u,T, '-o') % Find interpolated value for u=2680.78 new_u=2680.78; interp1(u, T, new_u) %Spline new_u = linspace(2500,3200,length(u)); new_T = interp1(u, T, new_u, 'spline'); figure(2) plot(u,T, new_u, new_T, '-o')

Page 19: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

19 NumericalTechniques

MATLABCourse,PartII-Solutions

Theinterpolatedvalueforu=2680.78KJ/kgis:

ans=

215.0000

i.,for 𝑢 = 2680.76 weget 𝑇 = 215.

Theplotbecomes:

Forspline,cubicwegetalmostthesame:

Thisisbecausethepointslistedabovearequitelinearintheirnature.

Page 20: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

20 NumericalTechniques

MATLABCourse,PartII-Solutions

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]

Solution:

MATLABScript:

T = [100, 150, 200, 250, 300, 400, 500]; u=[2506.7, 2582.8, 2658.1, 2733.7, 2810.4, 2967.9, 3131.6]; n=1; % 1.order polynomial(linear regression) p=polyfit(u,T,n); a=p(1) b=p(2), x=u; ymodel=a*x+b; plot(u,T,'o',u,ymodel)

a=

0.6415

b=

-1.5057e+003

Page 21: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

21 NumericalTechniques

MATLABCourse,PartII-Solutions

i.,wegetapolynomial 𝑝 = [0.6, −1.5 ∙ 10b].

ThePlotbecomes:

Task10: PolynomialRegression

Giventhefollowingdata:

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

→UsethepolyfitandpolyvalfunctionsinMATLABandcomparethemodelsusingdifferentordersofthepolynomial.

Usesubplotsandmakesuretoaddtitles,etc.

Page 22: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

22 NumericalTechniques

MATLABCourse,PartII-Solutions

[EndofTask]

Solution:

MATLABScript:

x=[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]; y=[23, 45, 60, 82, 111, 140, 167, 198, 200, 220]; for n=2: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

Theresultis:

Task11: Modelfitting

Giventhefollowingdata:

Page 23: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

23 NumericalTechniques

MATLABCourse,PartII-Solutions

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]

Solution:

MATLABScript:

clear, clc % Real Data height = [0, 1.7, 1.95, 2.60, 2.92, 4.04, 5.24]; flow = [0, 2.6, 3.6, 4.03, 6.45, 11.22, 30.61]; new_height = 0:0.5:6; % generating new height values used to test the model %linear------------------------- polyorder = 1; %linear p1 = polyfit(height, flow, polyorder) % 1.order model new_flow1 = polyval(p1,new_height); % We use the model to find new flow values %quadratic------------------------- polyorder = 2; %quadratic p2 = polyfit(height, flow, polyorder) % 2.order model new_flow2 = polyval(p2,new_height); % We use the model to find new flow values %cubic------------------------- polyorder = 3; %cubic p3 = polyfit(height, flow, polyorder) % 3.order model new_flow3 = polyval(p3,new_height); % We use the model to find new flow values %Plotting %We plot the original data together with the model found for comparison

Page 24: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

24 NumericalTechniques

MATLABCourse,PartII-Solutions

plot(height, flow, 'o', new_height, new_flow1, new_height, new_flow2, new_height, new_flow3) title('Model fitting') xlabel('height') ylabel('flow') legend('real data', 'linear model', 'quadratic model', 'cubic model')

Theresultbecomes:

p1 = 5.3862 -5.8380 p2 = 1.4982 -2.5990 1.1350 p3 = 0.5378 -2.6501 4.9412 -0.1001

Wherep1isthelinearmodel(1.order),p2isthequadraticmodel(2.order)andp3isthecubicmodel(3.order).

Thisgives:

1.ordermodel:

𝑝5 = 𝑎?𝑥 + 𝑎5 = 5.4𝑥 − 5.8

2.ordermodel:

𝑝2 = 𝑎?𝑥2 + 𝑎5𝑥 + 𝑎2 = 1.5𝑥2 − 2.6𝑥 + 1.1

3.ordermodel:

𝑝b = 𝑎?𝑥b + 𝑎5𝑥2 + 𝑎2𝑥 + 𝑎b = 0.5𝑥b − 2.7𝑥2 + 4.9𝑥 − 0.1

Wegetthefollowingplot:

Page 25: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

25 NumericalTechniques

MATLABCourse,PartII-Solutions

Discussion:

Asyouseethecubicmodel(3.order)givesthebestresult,i.e.,thecubicmodelfitsthedatabest.

Task12: NumericalDifferentiation

Giventhefollowingequation:

𝑦 = 𝑥b + 2𝑥2 − 𝑥 + 3

Find SeST analytically(use“penandpaper”).

Defineavectorxfrom-5to+5andusethedifffunctiontoapproximatethederivativeywith

respecttox(∆e∆T).

Comparethedataina2Darrayand/orplotboththeexactvalueof SeST andthe

approximationinthesameplot.

Increasenumberofdatapointtoseeifthereareanydifference.

Page 26: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

26 NumericalTechniques

MATLABCourse,PartII-Solutions

Dothesameforthefollowingfunctions:

𝑦 = sin(𝑥)

𝑦 = 𝑥i − 1

[EndofTask]

Solution:

Analyticallysolution:

𝑑𝑦𝑑𝑥 = 3𝑥2 + 4𝑥 − 1

MATLABScript:

x = -5:1:5; % Define the function y(x) y = x.^3 + 2*x.^2 - x + 3; % Plot the function y(x) plot(x,y) title('y') % Find nummerical solution to dy/dx dydx_num = diff(y)./diff(x); dydx_exact = 3*x.^2 + 4.*x -1; dydx = [[dydx_num, NaN]', dydx_exact'] % Plot nummerical vs analytical solution to dy/dx figure(2) plot(x,[dydx_num, NaN], x, dydx_exact) title('dy/dx') legend('numerical solution', 'analytical solution')

Plotof 𝑦(𝑥):

Page 27: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

27 NumericalTechniques

MATLABCourse,PartII-Solutions

Plotof SeST (Analyticalvs.numericalsolution):

Thevaluesare:

dydx = 42 54 22 31

Page 28: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

28 NumericalTechniques

MATLABCourse,PartII-Solutions

8 14 0 3 -2 -2 2 -1 12 6 28 19 50 38 78 63 NaN 94

Wedothesameforthefollowingfunctions:

𝑦 = sin(𝑥)

𝑑𝑦𝑑𝑥 = cos(𝑥)

𝑦 = 𝑥i − 1

𝑑𝑦𝑑𝑥 = 5𝑥l

→Theprocedureisexactlythesameandwillnotbeshownhere.

Task13: DifferentiationonPolynomials

Considerthefollowingequation:

𝑦 = 𝑥b + 2𝑥2 − 𝑥 + 3

UseDifferentiationonthePolynomialtofind SeST

[EndofTask]

Solution:

Analyticallysolution:

𝑑𝑦𝑑𝑥 = 3𝑥2 + 4𝑥 − 1

TheMATLABScript:

p=[1 2 -1 3]

Page 29: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

29 NumericalTechniques

MATLABCourse,PartII-Solutions

polyder(p)

Thesolutionis:

p =

1 2 -1 3

ans =

3 4 -1

Whichiscorrect.

Task14: DifferentiationonPolynomials

Findthederivativefortheproduct:

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

Usethepolyder(a,b)function.

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

Trybothmethods,toseeifyougetthesameanswer.

[EndofTask]

Solution:

MATLABScript:

% Define the polynomials p1 = [3 6 9]; p2 = [1 2]; % Method 1 polyder(p1,p2) % Method 2 p = conv(p1,p2) polyder(p)

Theresultis:

ans =

Page 30: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

30 NumericalTechniques

MATLABCourse,PartII-Solutions

9 24 21 p = 3 12 21 18 ans = 9 24 21

→Asexpected,theresultarethesameforthe2methodsusedabove.

𝑑( 3𝑥2 + 6𝑥 + 9 𝑥2 + 2𝑥 )𝑑𝑥 = 9𝑥2 + 24𝑥 + 21

Task15: NumericalIntegration

Usediff,quadandquadlonthefollowingequation:

𝑦 = 𝑥b + 2𝑥2 − 𝑥 + 3

Findtheintegralofywithrespecttox,evaluatedfrom-1to1

Comparethedifferentmethods.

Theexactsolutionis:

(𝑥b + 2𝑥2 − 𝑥 + 3)𝑑𝑥m

n=

𝑥l

4 +2𝑥b

3 −𝑥2

2 + 3𝑥n

m

=14 𝑏l − 𝑎l +

23 𝑏b − 𝑎b −

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

Comparetheresultwiththeexactsolution.

Repeatthetaskforthefollowingfunctions:

𝑦 = sin 𝑥

𝑦 = 𝑥i − 1

[EndofTask]

Solution:

MATLABScript:

clc x = -1:0.1:1; y = myfunc(x);

Page 31: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

31 NumericalTechniques

MATLABCourse,PartII-Solutions

plot(x,y) % Exact Solution a=-1; b=1; Iab = 1/4*(b^4-a^4 )+2/3*(b^3-a^3 )-1/2*(b^2-a^2 )+3*(b-a) % Method 1 avg_y = y(1:length(x)-1) + diff(y)/2; A1 = sum(diff(x).*avg_y) % Method 2 A2 = quad(@myfunc, -1,1) % Method 3 A3 = quadl(@myfunc, -1,1)

Wherethemathematicalfunctionisdefinedinthefollowingfunction:

function y = myfunc(x) y = x.^3 + 2*x.^2 - x + 3;

Theplotofthefunctionfrom-1to1isasfollows:

Theresultis:

Iab = 7.3333 A1 =

Page 32: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

32 NumericalTechniques

MATLABCourse,PartII-Solutions

7.3400 A2 = 7.3333 A3 = 7.3333

Theprocedureisthesamefor

Repeatthetaskforthefollowingfunctions:

𝑦 = sin 𝑥

sin 𝑥 𝑑𝑥m

n= cos(𝑥) nm = cos 𝑏 − cos(𝑎)

and:

𝑦 = 𝑥i − 1

(𝑥i − 1)𝑑𝑥m

n=

𝑥o

6 − 𝑥n

m

=𝑏o − 𝑎o

6 − (𝑏 − 𝑎)

TheMATLABCodeisnotshown,buttheprocedureisexactlythesameforthesefunctions.

Task16: IntegrationonPolynomials

Considerthefollowingequation:

𝑦 = 𝑥b + 2𝑥2 − 𝑥 + 3

Findtheintegralofywithrespecttox.

[EndofTask]

Solution:

MATLABScript:

p=[1 2 -1 3]; polyint(p)

Thesolutionis:

ans = 0.2500 0.6667 -0.5000 3.0000 0

Page 33: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

33 NumericalTechniques

MATLABCourse,PartII-Solutions

Thesolutionsanewpolynomial

[0.25,0.67,-0.5,3,0]

or:

0.25𝑥l + 0.67𝑥b − 0.5𝑥2 + 3𝑥

Weknowfromaprevioustaskthattheexactsolutionis:

(𝑥b + 2𝑥2 − 𝑥 + 3)𝑑𝑥m

n=

𝑥l

4 +2𝑥b

3 −𝑥2

2 + 3𝑥n

m

→Soweesetheansweriscorrect(asexpected).

Page 34: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

34

5 OptimizationTask17: Optimization

Giventhefollowingfunction:

𝑓 𝑥 = 𝑥b − 4𝑥

→Plotthefunction

→Findtheminimumforthisfunction

[EndofTask]

Solution:

Weplotthefunction:

MATLABCode:

%Optimization clear, clc x = -3:0.1:3;

Page 35: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

35 Optimization

MATLABCourse,PartII-Solutions

f = mysimplefunc2(x); plot(x, f) [xmin,fmin]=fminbnd(@mysimplefunc2, -3, 3)

Wherethefunctionisdefinedlikethis:

function f = mysimplefunc2(x) f = x.^3 - 4*x;

Thisgives:

xmin = 1.1547 fmin = -3.0792

Task18: Optimization-Rosenbrock'sBananaFunction

Giventhefollowingfunction:

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

ThisfunctionisknownasRosenbrock'sbananafunction.

→Plotthefunction

→Findtheminimumforthisfunction

[EndofTask]

Solution:

Thefunctionlookslikethis:

Page 36: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

36 Optimization

MATLABCourse,PartII-Solutions

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

MATLABScript:

[x,fval] = fminsearch(@bananafunc, [-1.2;1])

Wherethefunctionisdefined:

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

Thisgives:

x=

1.0000

1.0000

fval=

8.1777e-010

→Ithasaglobalminimumat (𝑥, 𝑦) = (1,1) where 𝑓(𝑥, 𝑦) = 0.

Wecanusethefollowingscripttoplotthefunction:

clear,clc

Page 37: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

37 Optimization

MATLABCourse,PartII-Solutions

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

Thisgives:

Page 38: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

38

6 ControlSystemToolboxNoTasks

Page 39: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

39

7 TransferFunctionsTask19: Transferfunction

UsethetffunctioninMATLABtodefinethetransferfunctionabove.SetK=2andT=3.

Type“help tf”intheCommandwindowtoseehowyouusethisfunction.

Example:

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

[EndofTask]

Solution:

Transferfunction:

𝐻 𝑠 =𝐾

𝑇𝑠 + 1

Withvalues:

𝐻 𝑠 =2

3𝑠 + 1

MATLABScript:

% Transfer function H=K/(Ts+1) K=2; T=3; num=[K]; den=[T, 1]; H = tf(num, den)

MATLABresponds:

Transferfunction:

Page 40: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

40 TransferFunctions

MATLABCourse,PartII-Solutions

2

-------

3 s + 1

Task20: 2.orderTransferfunction

Definethetransferfunctionusingthetffunction.

Set 𝐾 = 1,𝜔? = 1

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

𝜁 > 1

𝜁 = 1

0 < 𝜁 < 1

𝜁 = 0

𝜁 < 0

[EndofTask]

Solution:

Transferfunction:

𝐻 𝑠 =𝐾

𝑠𝜔?

2+ 2𝜁 𝑠

𝜔?+ 1

Wethenhavethat:

Page 41: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

41 TransferFunctions

MATLABCourse,PartII-Solutions

Wecanuse:

s = tf('s')

ThisspecifiesthetransferfunctionH(s)=s(Laplacevariable).

Youcanthenspecifytransferfunctionsdirectlyasrationalexpressionsins,e.g.,

s = tf('s'); H = (s+1)/(s^2+3*s+1)

MATLABScript(𝜁 = 1):

clc % Second order Transfer function % H(s)=K/((s/?_0 )^2+2? s/?_0 +1) % Define variables: K=1; w0=1;

Page 42: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

42 TransferFunctions

MATLABCourse,PartII-Solutions

zeta=1; % Define Transfer function s = tf('s'); H = K/((s/w0)^2 + 2*zeta*s/w0 + 1) step(H)

Theplotfromthestepresponsebecomes(𝜁 = 1):

Wecaneasilychangehevaluefor 𝜁 inthescript,wecane.g.,use 𝜁 = 2, 1, 0.2, 0, −0.2

WecanalsomodifytheprogramusingaForLoop:

clc % Second order Transfer function % H(s)=K/((s/?_0 )^2+2? s/?_0 +1) % Define variables: K=1; w0=1; for zeta=[-0.2, 0, 0.2, 1, 2] % Define Transfer function s = tf('s'); H = K/((s/w0)^2 + 2*zeta*s/w0 + 1)

Page 43: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

43 TransferFunctions

MATLABCourse,PartII-Solutions

step(H) pause end

Task21: TimeResponse

Giventhefollowingsystem:

𝐻 𝑠 =𝑠 + 1

𝑠2 − 𝑠 + 3

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

t=[0:0.01:10]

andusestep(H,t).

[EndofTask]

Solution:

MATLABScript:

% Define the transfer function num=[1,1]; den=[1,-1,3]; H=tf(num,den); % Define Time Interval t=[0:0.01:10]; % Step Response step(H,t);

Orusethismethod:

% Define the transfer function s = tf('s'); H = (s+1)/(s^2-s+3) % Define Time Interval t=[0:0.01:10]; % Step Response step(H,t);

Page 44: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

44 TransferFunctions

MATLABCourse,PartII-Solutions

TheStepresponsebecomes:

→Weseethesystemisunstable(whichwecouldseefromthetransferfunction!)

Task22: Integrator

ThetransferfunctionforanIntegratorisasfollows:

𝐻 𝑠 =𝐾𝑠

→Findthepole(s)

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

[EndofTask]

Solution:

Pole(s):

TheIntegratorhasapoleinorigo: 𝑝 = 0

Page 45: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

45 TransferFunctions

MATLABCourse,PartII-Solutions

InMATLAByoumayusethepolefunctioninordertofindthepoles.

% Integrator clc K=1; % Define the transfer function num = K; den = [1 0]; H = tf(num, den) pole(H)

StepResponse:

% Integrator K=1 % Define the transfer function s = tf('s'); H = K/s % Step Response step(H);

or:

% Integrator clc K=1; % Define the transfer function num = K; den = [1 0]; H = tf(num, den) % Step Response step(H);

Im(s)

Re(s)

Page 46: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

46 TransferFunctions

MATLABCourse,PartII-Solutions

YoucaneasilymodifytheprograminordertotrywithdifferentvaluesforK.ItisalsoeasytomodifytheprogramusingaForLoop,e.g.:

% Integrator clc for K = [0.2, 1, 5] % Define the transfer function num = K; den = [1 0]; H = tf(num, den) % Step Response step(H); hold on end

Theplotbecomes:

Page 47: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

47 TransferFunctions

MATLABCourse,PartII-Solutions

Wecanalsofindthemathematicalexpressionforthestepresponse(𝑦(𝑡))

𝑦 𝑠 = 𝐻 𝑠 𝑢(𝑠)

Where

𝑢 𝑠 =𝑈𝑠

TheLaplaceTransformationpairforastepisasfollows:

1𝑠 ⇔ 1

Thestepresponseofanintegratorthenbecomes:

𝑦 𝑠 = 𝐻 𝑠 𝑢 𝑠 =𝐾𝑠 ∙𝑈𝑠 = 𝐾𝑈

1𝑠2

WeusethefollowingLaplaceTransformationpairinordertofind 𝑦(𝑡):

1𝑠2 ⇔ 𝑡

Thenweget:

𝑦 𝑡 = 𝐾𝑈𝑡

Page 48: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

48 TransferFunctions

MATLABCourse,PartII-Solutions

-SoweseethatthestepresponseoftheintegratorisaRamp.

Conclusion:AbiggerKwillgiveabiggerslope(InNorwegian:“stigningstall”)andtheintegrationwillgofaster.

Task23: 1.ordersystem

Thetransferfunctionfora1.ordersystemisasfollows:

𝐻 𝑠 =𝐾

𝑇𝑠 + 1

→Findthepole(s)

→PlottheStepresponse.UsethestepfunctioninMATLAB.

• Stepresponse1:UsedifferentvaluesforK,e.g.,K=0.5,1,2.SetT=1• Stepresponse2:UsedifferentvaluesforT,e.g.,T=0.2,0.5,1,2,4.SetK=1

[EndofTask]

Solution:

Pole(s):

A1.ordersystemhasapole: 𝑝 = − 56

InMATLAByoumayusethepolefunctioninordertofindthepoles.

StepResponse:

MATLABScript:

% 1.order system clc % Define the transfer function K=1;

Im(s)

Re(s)-1/T

Page 49: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

49 TransferFunctions

MATLABCourse,PartII-Solutions

T=1; num = K; den = [T 1]; H = tf(num, den) pole(H) % Step Response step(H);

ForK=1andT=1wegetthefollowing:

Transfer function: 1 ----- s + 1 ans = -1

Thepoleis-1.

WecaneasilymodifytheprogramforothervaluesforKandT.

Page 50: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

50 TransferFunctions

MATLABCourse,PartII-Solutions

HereisanexamplewherewesetK=0.5,1,2(T=1):

% 1.order system clc t=[0:0.5:10]; T=1; K=0.5; num = K; den = [T 1]; H1 = tf(num, den); K=1; num = K; den = [T 1]; H2 = tf(num, den); K=2; num = K; den = [T 1]; H3 = tf(num, den); % Step Response step(H1,H2,H3,t); legend('K=0.5', 'K=1', 'K=2');

Thisgivesthefollowingplot:

WecouldalsohaveusedasimpleForLoopforthis.

Page 51: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

51 TransferFunctions

MATLABCourse,PartII-Solutions

→Conclusion:Kdefineshowmuchtheinputsignalisamplifiedthroughthesystem.

HereisanexamplewherewesetT=0.2,0.5,1,2,4(K=1):

MATLABCode:

% 1.order system clc t=[0:0.5:10]; K=1; T=0.2; num = K; den = [T 1]; H1 = tf(num, den); T=0.5; num = K; den = [T 1]; H2 = tf(num, den); T=1; num = K; den = [T 1]; H3 = tf(num, den); T=2; num = K; den = [T 1]; H4 = tf(num, den); % Step Response step(H1,H2,H3,H4,t); legend('T=0.2', 'T=0.5', 'T=1', 'T=2');

Page 52: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

52 TransferFunctions

MATLABCourse,PartII-Solutions

→Coclusion:WeseefromFigureabovethatsmallerT(Timeconstant)givesfasterresponse.

Mathematicalexpressionforthestepresponse(𝒚(𝒕)).

Wecomparethesimulationresultsabovewiththemathematicalexpressionforthestepresponse(𝑦(𝑡)).

𝑦 𝑠 = 𝐻 𝑠 𝑢(𝑠)

Where

𝑢 𝑠 =𝑈𝑠

WeuseinverseLaplaceandfindthecorrespondingtransformationpairinordertofind𝑦(𝑡).Thisgives:

𝑦 𝑠 =𝐾

𝑇𝑠 + 1 ∙𝑈𝑠

WeusethefollowingLaplacetransformpair:

𝑘𝑇𝑠 + 1 𝑠 ⇔ 𝑘(1 − 𝑒{U/6)

Thisgives:

𝑦 𝑡 = 𝐾𝑈(1 − 𝑒{U/6)

AsimplesketchofstepresponseisT(= 𝑇ob):

Page 53: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

53 TransferFunctions

MATLABCourse,PartII-Solutions

Task24: 2.ordersystem

Thetransferfunctionfora2.Ordersystemisasfollows:

𝐻 𝑠 =𝐾𝜔?2

𝑠2 + 2𝜁𝜔?𝑠 + 𝜔?2=

𝐾𝑠𝜔?

2+ 2𝜁 𝑠

𝜔?+ 1

Where

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

→Findthepole(s)

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

[EndofTask]

Solution:

Poles:

Poles: 𝑠2 + 2𝜁𝜔?𝑠 + 𝜔?2 = 0 gives:

Page 54: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

54 TransferFunctions

MATLABCourse,PartII-Solutions

𝑝5, 𝑝2 = −𝜁𝜔? ± 𝜁2 − 1𝜔?

StepResponse:

Wethenhavethat:

WecreatethefollowingMATLABScriptinordertoprovethis:

% Second order Transfer function clc t=[0:0.5:10]; % Define variables: K=1; w0=1; % Define Transfer function zeta=0.2; num = K; den = [(1/w0)^2, 2*zeta/w0, 1] H1 = tf(num, den) zeta=1;

Page 55: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

55 TransferFunctions

MATLABCourse,PartII-Solutions

num = K; den = [(1/w0)^2, 2*zeta/w0, 1] H2 = tf(num, den) zeta=2; num = K; den = [(1/w0)^2, 2*zeta/w0, 1] H3 = tf(num, den) step(H1, H2, H3, t) legend('zeta=0.2', 'zeta=1', 'zeta=')

Thisgivesthefollowingresults:

Conclusion:Weseetheresultsareasexpected.

𝜁 = 0.2 givesa“underdamped”system

𝜁 = 1 givesa“criticallydamped”system

𝜁 = 2 givesa“overdamped”system

Page 56: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

56 TransferFunctions

MATLABCourse,PartII-Solutions

Task25: 2.ordersystem–SpecialCase

Specialcase:When 𝜁 > 0 andthepolesarerealanddistinctwehave:

𝐻 𝑠 =𝐾

(𝑇5𝑠 + 1)(𝑇2𝑠 + 1)

Weseethatthissystemcanbeconsideredastwo1.ordersystemsinseries.

𝐻 𝑠 = 𝐻5 𝑠 𝐻5 𝑠 =𝐾

(𝑇5𝑠 + 1)∙

1(𝑇2𝑠 + 1)

=𝐾

(𝑇5𝑠 + 1)(𝑇2𝑠 + 1)

Set 𝑇5 = 2 and 𝑇2 = 5

→Findthepole(s)

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

[EndofTask]

Solution:

Poles:

Thepolesare:

𝑝5 = −1𝑇5, 𝑝2 = −

1𝑇2

StepResponse:

Page 57: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

57 TransferFunctions

MATLABCourse,PartII-Solutions

Wewillfindthemathematicalexpressionforthestepresponse(𝑦(𝑡))inordertoanalyzetheresultsfromthesimulations.

WeuseinverseLaplaceandfindthecorrespondingtransformationpairinordertofind𝑦(𝑡)).

Thestepresponseforthissystemis:

𝑦 𝑠 = 𝐻 𝑠 𝑢(𝑠)

Where

𝑢 𝑠 =𝑈𝑠

Thenweget:

𝑦 𝑠 =𝐾𝑈

(𝑇5𝑠 + 1)(𝑇2𝑠 + 1)𝑠

WeusethefollowingLaplacetransformpair:

1(𝑇5𝑠 + 1)(𝑇2𝑠 + 1)𝑠

⇔ 1 +1

𝑇2 − 𝑇5(𝑇5𝑒

{ U6~ − 𝑇2𝑒{U/6�)

Thenweget:

Page 58: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

58 TransferFunctions

MATLABCourse,PartII-Solutions

𝑦 𝑡 = 𝐾𝑈 1 +1

𝑇2 − 𝑇5(𝑇5𝑒

{ U6~ − 𝑇2𝑒{U/6�)

Weseethatthestepresponseisa(weighted)sumoftwoexponentialfunctions.Theresponsewillbewithnoovershotanditwillbeoverdamped,asshowninthesimulationsabove.

Page 59: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

59

8 State-SpaceModelsTask26: State-spacemodel

Implementthefollowingequationsasastate-spacemodelinMATLAB:

𝑥5 = 𝑥2

2𝑥2 = −2𝑥5−6𝑥2+4𝑢5+8𝑢2

𝑦 = 5𝑥5+6𝑥2+7𝑢5

→FindtheStepResponse

→Findthetransferfunctionfromthestate-spacemodelusingMATLABcode.

[EndofTask]

Solution:

Firstwedo:

𝑥5 = 𝑥2

𝑥2 = −𝑥5−3𝑥2+2𝑢5+4𝑢2

𝑦 = 5𝑥5+6𝑥2+7𝑢5

Wehavethat:

𝑥 = 𝐴𝑥 + 𝐵𝑢

𝑦 = 𝐶𝑥 + 𝐷𝑢

Thisgives:

𝑥5𝑥2

= 0 1−1 −3

𝑥5𝑥2 + 0 0

2 4�

𝑢5𝑢2

𝑦 = 5 6�

𝑥5𝑥2 + 7 0

𝑢5𝑢2

MATLABScript:

Page 60: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

60 DiscreteSystems

MATLABCourse,PartII-Solutions

% Define State-space model A = [0 1; -1 -3]; B = [0 0; 2 4]; C = [5 6]; D = [7 0]; sys = ss(A, B, C, D) step(sys)

StepResponse:

Note!ThisisaaMISOsystem(MultipleInput,SingleOutput).

𝐻5 =𝑦𝑢5, 𝐻2 =

𝑦𝑢2

Thetransferfunctionfromthestate-spacemodel:

% Define State-space model A = [0 1; -1 -3]; B = [0 0; 2 4]; C = [5 6]; D = [7 0]; sys = ss(A, B, C, D) H = tf(sys)

Page 61: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

61 DiscreteSystems

MATLABCourse,PartII-Solutions

Theresultbecomes:

Transfer function from input 1 to output: 7 s^2 + 33 s + 17 ----------------- s^2 + 3 s + 1 Transfer function from input 2 to output: 24 s + 20 ------------- s^2 + 3 s + 1

Asyouseeweget2transferfunctionsbecausethisisaMISOsystem(MultipleInput,SingleOutput).

𝐻5 =𝑦𝑢5, 𝐻2 =

𝑦𝑢2

Youshouldalsotrythefunctionsss2tfandtf2ss.

Task27: Mass-spring-dampersystem

Givenamass-spring-dampersystem:

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

Thestate-spacemodelforthesystemis:

𝑥5𝑥2

=0 1

−𝑘𝑚 −

𝑐𝑚

𝑥5𝑥2 +

01𝑚

𝑢

𝑦 = 1 0𝑥5𝑥2

Definethestate-spacemodelaboveusingthessfunctioninMATLAB.

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

Page 62: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

62 DiscreteSystems

MATLABCourse,PartII-Solutions

→ApplyastepinF(u)andusethestepfunctioninMATLABtosimulatetheresult.

→Findthetransferfunctionfromthestate-spacemodel

[EndofTask]

Solution:

MATLABScript:

clc % Define variables k = 50; c = 1; m = 1; % Define State-space model A = [0 1; -k/m -c/m]; B = [0; 1/m]; C = [1 0]; D = [0]; sys = ss(A, B, C, D) step(sys)

Theresultbecomes:

Page 63: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

63 DiscreteSystems

MATLABCourse,PartII-Solutions

Transferfunction:

H = tf(sys)

Thisgives:

Transfer function: 1 ------------ s^2 + s + 50

Task28: BlockDiagram

Findthestate-spacemodelfromtheblockdiagrambelowandimplementitinMATLAB.

Set

𝑎5 = 5

𝑎2 = 2

Andb=1,c=1

→SimulatethesystemusingthestepfunctioninMATLAB

[EndofTask]

Solution:

Page 64: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

64 DiscreteSystems

MATLABCourse,PartII-Solutions

Ageneralstate-spacemodel:

𝑥 = 𝐴𝑥 + 𝐵𝑢

𝑦 = 𝐶𝑥 + 𝐷𝑢

Wegetthefollowingstate-spacemodelfromtheblockdiagram:

𝑥5 = −𝑎5𝑥5 − 𝑎2𝑥2 + 𝑏𝑢

𝑥2 = −𝑥2 + 𝑢

𝑦 = 𝑥5 + 𝑐𝑥2

Thisgives:

𝑥5𝑥2

= −𝑎5 −𝑎20 −1

𝑥5𝑥2 + 𝑏

1�

𝑢

𝑦 = 1 𝑐�

𝑥5𝑥2

Simulation:

Task29: Discretization

Thestate-spacemodelforthesystemis:

Page 65: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

65 DiscreteSystems

MATLABCourse,PartII-Solutions

𝑥5𝑥2

=0 1

−𝑘𝑚 −

𝑐𝑚

𝑥5𝑥2 +

01𝑚

𝑢

𝑦 = 1 0𝑥5𝑥2

Setsomearbitraryvaluesfor 𝑘, 𝑐 and 𝑚.

FindthediscreteState-spacemodelusingMATLAB.

[EndofTask]

Solution:

Code:

clc % Define variables k = 50; c = 1; m = 1; % Define State-space model A = [0 1; -k/m -c/m]; B = [0; 1/m]; C = [1 0]; D = [0]; sys = ss(A, B, C, D) Ts=0.1; % Sampling Time sysd = c2d(sys, Ts); A_disc = sysd.A B_disc = sysd.B C_disc = sysd.C D_disc = sysd.D

Thisgivesthefollowingdiscretesystem:

A_disc = 0.7680 0.0874 -4.3715 0.6805 B_disc = 0.0046 0.0874 C_disc = 1 0 D_disc = 0

Note!Wehavetospecifythesamplingtimewhenusingthec2dfunction.

Page 66: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

66

9 FrequencyResponseTask30: 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]

Solutions:

→Whatisthebreakfrequency?

Solution:

Page 67: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

67 FrequencyResponse

MATLABCourse,PartII-Solutions

𝜔 =1𝑇 =

12 = 0.5

→Setupthemathematicalexpressionsfor 𝐴(𝜔) and 𝜙(𝜔).

Solution:

𝐻(𝑗𝜔) S� = 20𝑙𝑜𝑔4 − 20𝑙𝑜𝑔 (2𝜔)2 + 1

∠𝐻(𝑗𝜔) = −arctan(2𝜔)

→PlotthefrequencyresponseofthesysteminabodeplotusingthebodefunctioninMathScript.

Solution:

MATLABScript:

clc % Transfer function K = 4; T = 2; num = [K]; den = [T, 1]; H = tf(num, den) % Bode Plot bode(H) grid

TheBodePlotbecomes:

Page 68: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

68 FrequencyResponse

MATLABCourse,PartII-Solutions

→Find 𝐴(𝜔) and 𝜙(𝜔) forthefollowingfrequenciesusingMathScriptcode:

Solution:

MATLABScript:

clc % Transfer function K = 4; T = 2; num = [K]; den = [T, 1]; H = tf(num, den) % Bode Plot bode(H) grid % Margins and Phases w=[0.1, 0.16, 0.25, 0.4, 0.625,2.5]; [mag, phase] = bode(H, w); magdB=20*log10(mag); %convert to dB

Page 69: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

69 FrequencyResponse

MATLABCourse,PartII-Solutions

magdB phase

Theresultfromthescriptis:

Transfer function: 4 ------- 2 s + 1 magdB(:,:,1) = 11.8709 magdB(:,:,2) = 11.6178 magdB(:,:,3) = 11.0721 magdB(:,:,4) = 9.8928 magdB(:,:,5) = 7.9546 magdB(:,:,6) = -2.1085 phase(:,:,1) = -11.3099 phase(:,:,2) = -17.7447 phase(:,:,3) = -26.5651 phase(:,:,4) = -38.6598 phase(:,:,5) = -51.3402 phase(:,:,6) = -78.6901

Weinsertthevaluesintothetableandget:

𝜔 𝐴(𝜔) 𝜙(𝜔)

0.1 11.9 -11.3

0.16 11.6 -17.7

0.25 11.1 -26.5

0.4 9.9 -38.7

0.625 7.8 -51.3

Page 70: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

70 FrequencyResponse

MATLABCourse,PartII-Solutions

2.5 -2.1 -78.6

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

Solution:

MATLABScript:

clc % Transfer function K = 4; T = 2; num = [K]; den = [T, 1]; H = tf(num, den) % Frequency List wlist=[0.1, 0.16, 0.25, 0.4, 0.625,2.5]; N= length(wlist); for i=1:N gain(i) = 20*log10(4) - 20*log10(sqrt((2*wlist(i))^2+1)); phase(i) = -atan(2*wlist(i)); phasedeg(i) = phase(i) * 180/pi; %convert to degrees end % Print to Screen gain_data = [wlist; gain]' phase_data=[wlist; phasedeg]' %------------------------------------------ % Check with results from the bode function [gain2, phase2,w] = bode(H, wlist); gain2dB=20*log10(gain2); %convert to dB % Print to Screen gain2dB phase2

Page 71: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

71 FrequencyResponse

MATLABCourse,PartII-Solutions

Theoutputis:

gain_data = 0.1000 11.8709 0.1600 11.6178 0.2500 11.0721 0.4000 9.8928 0.6250 7.9546 2.5000 -2.1085 phase_data = 0.1000 -11.3099 0.1600 -17.7447 0.2500 -26.5651 0.4000 -38.6598 0.6250 -51.3402 2.5000 -78.6901

→Weseetheresultsarethesameastheresultfoundusingthebodefunction.

Task31: BodeDiagram

Wehavethefollowingtransferfunction:

𝐻 𝑆 =(5𝑠 + 1)

2𝑠 + 1 (10𝑠 + 1)

→Whatisthebreakfrequencies?

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

→PlotthefrequencyresponseofthesysteminabodeplotusingthebodefunctioninMATLAB.Discusstheresults.

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

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

[EndofTask]

Solutions:

→Whatisthebreakfrequencies?

Solution:

Page 72: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

72 FrequencyResponse

MATLABCourse,PartII-Solutions

𝜔5 =1𝑇5=15 = 1

𝜔2 =1𝑇2=12 = 0.5

𝜔b =1𝑇b=110 = 0.1

→Setupthemathematicalexpressionsfor 𝐴(𝜔) and 𝜙(𝜔).

Solution:

𝐻(𝑗𝜔) S� = 20𝑙𝑜𝑔 (5𝜔)2 + 1 − 20𝑙𝑜𝑔 (2𝜔)2 + 1 − 20𝑙𝑜𝑔 (10𝜔)2 + 1

∠𝐻(𝑗𝜔) = arctan(5𝜔) − arctan(2𝜔) − arctan(10𝜔)

→PlotthefrequencyresponseofthesysteminabodeplotusingthebodefunctioninMATLAB.

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

Solution:

MATLABScript:

clc clf % Transfer function num=[5,1]; den1=[2, 1]; den2=[10,1] den = conv(den1,den2); H = tf(num, den) % Bode Plot bode(H) grid % Margins and Phases w=[0.01, 0.1, 0.2, 0.5, 1, 10, 100]; [mag, phase] = bode(H, wlist);

Page 73: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

73 FrequencyResponse

MATLABCourse,PartII-Solutions

magdB=20*log10(mag); %convert to dB % Print to Screen magdB phase

BodePlot:

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

Solution:

→SameprocedureasforpreviousTask,thecodewillnotbeshownhere.

Task32: FrequencyResponseAnalysis

Giventhefollowingsystem:

Processtransferfunction:

𝐻� =𝐾𝑠

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

Page 74: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

74 FrequencyResponse

MATLABCourse,PartII-Solutions

Measurement(sensor)transferfunction:

𝐻� = 𝐾�

Where 𝐾� = 1.

Controllertransferfunction(PIController):

𝐻� = 𝐾� +𝐾�𝑇 𝑠

SetKp=1,5ogTi=1000sec.

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

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

→Findthebandwidths 𝜔U, 𝜔�, 𝜔Z fromtheplotabove.

→PlotthestepresponsefortheTrackingtransferfunction 𝑇(𝑠)

[EndofTask]

Solution:

MATLABScript:

% Frequency Response Analysis clear clc close all %closes all opened figures. They will be opened as the script is executed. s=tf('s'); %Defines s to be the Laplace variable used in transfer functions %Model parameters: Ks=0.556; %(kg/s)/% A=13.4; %m2

Page 75: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

75 FrequencyResponse

MATLABCourse,PartII-Solutions

rho=145; %kg/m3 transportdelay=250; %sec %Defining the process transfer function: K=Ks/(rho*A); Hp=K/s; %Defining sensor transfer function: Km=1; Hs=tf(Km); %Defining sensor transfer function (just a gain in this example) %Defining controller transfer function: Kp=1.5; Ti=1000; Hc=Kp+Kp/(Ti*s); %PI controller transfer function %Calculating control system transfer functions: L=Hc*Hp*Hs; %Calculating Loop transfer function T=L/(1+L) %Calculating tracking transfer function S=1-T; %Calculating sensitivity transfer function figure(1) bodemag(L,T,S), grid %Plots maginitude of L, T, and S in Bode diagram figure(2) step(T), grid %Simulating step response for control system (tracking transfer function)

TheBodeplotbecomes:

Page 76: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

76 FrequencyResponse

MATLABCourse,PartII-Solutions

Wefindthebandwidthsintheplotaccordingtothesketchbelow:

Page 77: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

77 FrequencyResponse

MATLABCourse,PartII-Solutions

Wechangethescalingformoredetails:

Igetthefollowingvalues:

𝝎𝒄 = 𝟎. 𝟎𝟎𝟎𝟕𝟑

𝝎𝒔 = 𝟎. 𝟎𝟎𝟎𝟑𝟐

𝝎𝒕 = 𝟎. 𝟎𝟎𝟏𝟐

ThestepresponsefortheTrackingtransferfunction 𝑇(𝑠):

Page 78: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

78 FrequencyResponse

MATLABCourse,PartII-Solutions

Task33: StabilityAnalysis

Giventhefollowingsystem:

𝐻 𝑆 =1

𝑠 𝑠 + 1 2

Wewillfindthecrossover-frequenciesforthesystemusingMATLAB.Wewillalsofindalsothegainmarginsandphasemarginsforthesystem.

Plotabodediagramwherethecrossover-frequencies,GMandPMareillustrated.Tip!UsethemarginfunctioninMATLAB.

[EndofTask]

Solution:

MATLABCode:

clear clc % Transfer function

Page 79: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

79 FrequencyResponse

MATLABCourse,PartII-Solutions

num=[1]; den1=[1,0]; den2=[1,1]; den3=[1,1]; den = conv(den1,conv(den2,den3)); H = tf(num, den); % Bode Plot figure(1) bode(H) grid % Margins and Phases wlist=[0.01, 0.1, 0.2, 0.5, 1, 10, 100]; [mag, phase,w] = bode(H, wlist); magdB=20*log10(mag); %convert to dB % Display magnitude and phase data %magdB %phase % Crossover Frequency------------------------------------- [gm, pm, gmf, pmf] = margin(H); gm_dB = 20*log10(gm); gm_dB pm gmf pmf figure(2) margin(H)

TheBodeplotbecomes:

Page 80: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

80 FrequencyResponse

MATLABCourse,PartII-Solutions

Wecanfindthecrossover-frequencies,thegainmarginsandphasemarginsforthesystemfromtheplotabove.

Butifweusethemarginfunction:

margin(H)

wegetthefollowingplot:

Page 81: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

81 FrequencyResponse

MATLABCourse,PartII-Solutions

Wecanaloscalculatethevaluesusingthesamemarginfunction:

[gm, pm, gmf, pmf] = margin(H); gm_dB = 20*log10(gm);

Thisgives:

gm_dB = 6.0206 pm = 21.3877 gmf = 1 pmf = 0.6823

Page 82: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

82

10 AdditionalTasksTask34: ODESolvers

Usetheode45functiontosolveandplottheresultsofthefollowingdifferentialequationintheinterval [𝑡?, 𝑡A]:

𝟑𝒘D +𝟏

𝟏 + 𝒕𝟐 𝒘 = 𝒄𝒐𝒔𝒕, 𝑡? = 0, 𝑡A = 5,𝑤 𝑡? = 1

[EndofTask]

Solution:

Werewritetheequation:

𝑤D =𝑐𝑜𝑠𝑡 − 𝑤

1 + 𝑡23

Thisgives:

function dw = diff_task34(t,w) dw = (cos(t) - (w/(1+t^2)))/3;

and:

tspan=[0 5]; w0=1; [t,w]=ode23(@diff_task34, tspan, w0); plot(t,w)

Theresultbecomes:

Page 83: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

83 AdditionalTasks

MATLABCourse,PartII-Solutions

Task35: Mass-spring-dampersystem

Givenamass-spring-dampersystem:

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

Thestate-spacemodelforthesystemis:

𝑥5𝑥2

=0 1

−𝑘𝑚 −

𝑐𝑚

𝑥5𝑥2 +

01𝑚

𝑢

Definethestate-spacemodelaboveusingthessfunctioninMATLAB.

Page 84: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

84 AdditionalTasks

MATLABCourse,PartII-Solutions

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

→SolveandPlotthesystemusingoneormoreofthebuilt-insolvers(ode32,ode45)inMATLAB.ApplyastepinF(u).

[EndofTask]

Solution:

MATLABScript:

clc tspan=[0 10]; x0=[0.5; 0]; [t,y]=ode23(@msd_diff, tspan,x0); plot(t,y) legend('x1', 'x2')

Thedifferentialequationsisdefinedinthefunctionmsd_diff(msd_diff.m):

function dx = msd_diff(t,x) % Define variables k = 50; c = 1; m = 1; u=1; % Define State-space model A = [0 1; -k/m -c/m]; B = [0; 1/m]; dx = A*x + B*u;

Results:

Page 85: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

85 AdditionalTasks

MATLABCourse,PartII-Solutions

Task36: NumericalIntegration

Givenapistoncylinderdevice:

→Findtheworkproducedinapistoncylinderdevicebysolvingtheequation:

𝑊 = 𝑃𝑑𝑉«�

«~

Page 86: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

86 AdditionalTasks

MATLABCourse,PartII-Solutions

Assumetheidealgaslowapplies:

𝑃𝑉 = 𝑛𝑅𝑇

where

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

Wealsoassumethatthepistoncontains1molofgasat300Kandthatthetemperatureisconstantduringtheprocess. 𝑉5 = 1𝑚b, 𝑉2 = 5𝑚b

Useboththequadandquadlfunctions.Comparewiththeexactsolutionbysolvingtheintegralanalytically.

[EndofTask]

Solution:

Westartbysolvingtheintegralanalytically:

𝑊 = 𝑃𝑑𝑉«�

«~=

𝑛𝑅𝑇𝑉 𝑑𝑉

«�

«~= 𝑛𝑅𝑇

1𝑉 𝑑𝑉 = 𝑛𝑅𝑇𝑙𝑛

𝑉2𝑉5

«�

«~

Insertingvaluesgives:

𝑊 = 1𝑘𝑚𝑜𝑙×8.314𝑘𝐽

𝑘𝑚𝑜𝑙𝐾 ×300𝐾× ln5𝑚b

1𝑚b = 4014𝑘𝐽

Note!Becausethisworkispositive,itisproducedby(andnoton)thesystem.

MATLABScript:

clear, clc quad(@piston_func, 1, 5) quadl(@piston_func, 1, 5)

wherethefunctionisdefinedinanownfunctioncalled“piston_func”:

function P = piston_func(V) % Define constants n = 1;

Page 87: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

87 AdditionalTasks

MATLABCourse,PartII-Solutions

R = 8.315; T=300; P=n*R*T./V;

Runningthescriptgives:

ans =

4.0147e+003

ans =

4.0147e+003

Task37: State-spacemodel

Thefollowingmodelofapendulumisgiven:

𝑥5 = 𝑥2

𝑥2 = −𝑔𝑟 𝑥5 −

𝑏𝑚𝑟2 𝑥2

wheremisthemass,risthelengthofthearmofthependulum,gisthegravity,bisafrictioncoefficient.

→Definethestate-spacemodelinMATLAB

→SolvethedifferentialequationsinMATLABandplottheresults.

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

[EndofTask]

Solution:

State-spacemodel:

𝑥5𝑥2

=0 1

−𝑔𝑟 −

𝑏𝑚𝑟2

𝑥5𝑥2

MATLABScript:

clear,clc

Page 88: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

88 AdditionalTasks

MATLABCourse,PartII-Solutions

tspan=[0 100]; x0=[0.5; 0]; [t,y]=ode23(@pendulum_diff, tspan,x0); plot(t,y) legend('x1', 'x2')

Thefunctionisdefined:

function dx = pendulum_diff(t,x) % Define variables and constants g = 9.81; m = 8; r = 5; b = 10; % Define State-space model A = [0 1; -g/r -b/(m*r^2)]; dx = A*x;

Theresultsbecome:

Page 89: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

89 AdditionalTasks

MATLABCourse,PartII-Solutions

Task38: lsim

Givenamass-spring-dampersystem:

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

Thestate-spacemodelforthesystemis:

𝑥5𝑥2

=0 1

−𝑘𝑚 −

𝑐𝑚

𝑥5𝑥2 +

01𝑚

𝑢

𝑦 = 1 0𝑥5𝑥2

→SimulatethesystemusingthelsimfunctionintheControlSystemToolbox.

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

[EndofTask]

Solution:

MATLABScript:

clear, clc % Define variables k = 50; c = 1; m = 1; % Define State-space model A = [0 1; -k/m -c/m]; B = [0; 1/m]; C = [1 0]; D = [0]; sssys = ss(A, B, C, D);

Page 90: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

90 AdditionalTasks

MATLABCourse,PartII-Solutions

t = 0:0.01:5; u = eye(length(t),1); x0=[0.5; 0]; lsim(sssys, u, t, x0)

Theresultbecomes:

Page 91: MATLAB Solutions - Part 2 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB... · Task 27: Mass-spring-damper system ... Create a script in MATLAB (.m

Hans-PetterHalvorsen,M.Sc.

E-mail:[email protected]

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

UniversityCollegeofSoutheastNorway

www.usn.no