Modelling and Simulation in MATLAB - Overview

Post on 04-Jan-2017

230 views 9 download

transcript

Modelling,Simulation&Control

Hans-PetterHalvorsen,M.Sc.

QuickStartTutorial

WhatisMATLAB?• MATLABisatoolfortechnicalcomputing,computationandvisualizationinanintegratedenvironment.

• MATLABisanabbreviationforMATrixLABoratory• ItiswellsuitedforMatrix manipulationandproblemsolvingrelatedtoLinearAlgebra,Modelling,SimulationandControlApplications

• PopularinUniversities, TeachingandResearch

Lessons1. SolvingDifferentialEquations(ODEs)2. DiscreteSystems3. Interpolation/CurveFitting4. NumericalDifferentiation/Integration5. Optimization6. TransferFunctions/State-spaceModels7. FrequencyResponse

Lesson1Solving ODEsinMATLAB- OrdinaryDifferentialEquations

DifferentialEquationsExample:

Note!

TheSolutioncanbeprovedtobe(willnotbeshownhere):

T = 5;a = -1/T;x0 = 1;t = [0:1:25];

x = exp(a*t)*x0;

plot(t,x);grid

Students:Trythisexample

Usethefollowing:

Where

TistheTimeconstant

DifferentialEquations

T = 5;a = -1/T;x0 = 1;t = [0:1:25];

x = exp(a*t)*x0;

plot(t,x);grid

Problemwiththismethod:WeneedtosolvetheODEbeforewecanplotit!!

UsingODESolversinMATLABExample:Step1:DefinethedifferentialequationasaMATLABfunction(mydiff.m):

Step2:Useoneofthebuilt-inODEsolver(ode23,ode45,...)inaScript.

Students:Trythisexample.Doyougetthesameresult?

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

clearclc

tspan = [0 25];x0 = 1;

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

tspan

x0

HigherOrderODEs

InordertousetheODEsinMATLABweneedreformulateahigherordersystemintoasystemoffirstorderdifferentialequations

Mass-Spring-DamperSystem

Example(2.orderdifferentialequation):

HigherOrderODEs

InordertousetheODEsinMATLABweneedreformulateahigherordersystemintoasystemoffirstorderdifferentialequations

Mass-Spring-DamperSystem:

Weset: Thisgives: Finally:

NowwearereadytosolvethesystemusingMATLAB

Step1:DefinethedifferentialequationasaMATLABfunction(mass_spring_damper_diff.m):

Step2:Usethebuilt-inODEsolverinascript.

Students:Trythisexample

function dx = mass_spring_damper_diff(t,x)

k = 1;m = 5;c = 1;F = 1;

dx = zeros(2,1); %Initialization

dx(1) = x(2);dx(2) = -(k/m)*x(1)-(c/m)*x(2)+(1/m)*F;

clearclc

tspan = [0 50];x0 = [0;0];

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

Students:Trywithdifferentvaluesfork,m,candF

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

...[t,x] = ode23(@mass_spring_damper_diff,tspan,x0);plot(t,x(:,2))

function dx = mass_spring_damper_diff(t,x, param)

k = param(1);m = param(2);c = param(3);F = param(4);

dx = zeros(2,1);

dx(1) = x(2);dx(2) = -(k/m)*x(1) - (c/m)*x(2) + (1/m)*F;

Step1:DefinethedifferentialequationasaMATLABfunction(mass_spring_damper_diff.m):

Students:Trythisexample

Forgreaterflexibilitywewanttobeabletochangetheparametersk,m,c,andFwithoutchangingthefunction,onlychangingthescript.Abetterapproachwouldbetopasstheseparameterstothefunctioninstead.

clearclcclose all

tspan = [0 50];x0 = [0;0];

k = 1;m = 5;c = 1;F = 1;param = [k, m, c, F];

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

Step2:Usethebuilt-inODEsolverinascript:

Students:Trythisexample

Whatsnext?

Self-pacedTutorialswithlotsofExercisesandVideoresources

DoasmanyExercisesaspossible! TheonlywaytolearnMATLABisbydoingExercisesandhands-onCoding!!!

LearningbyDoing!

Lesson 2

• DiscreteSystems

DiscreteSystems

• Whendealingwithcomputersimulations,weneedtocreateadiscreteversionofoursystem.

• Thismeansweneedtomakeadiscreteversionofourcontinuousdifferentialequations.

• Actually,thebuilt-inODEsolversinMATLABusedifferentdiscretizationmethods

• Interpolation,CurveFitting,etc.isalsobasedonasetofdiscretevalues(datapointsormeasurements)

• ThesamewithNumericalDifferentiationandNumericalIntegration

• etc.

x y

0 15

1 10

2 9

3 6

4 2

5 0

Discretevalues

DiscreteApproximationofthetimederivativeEulerbackwardmethod:

Eulerforwardmethod:

DiscreteSystems

DiscretizationMethods

Eulerforwardmethod:

Eulerbackwardmethod:

OthermethodsareZeroOrderHold(ZOH),Tustin’smethod,etc.

Simplertouse!

MoreAccurate!

DiscreteSystems

DifferentDiscreteSymbolsandmeanings

Present Value:

Previous Value:

Next (Future)Value:

Note!DifferentNotationisusedindifferentlitterature!

DiscreteSystems

DiscreteSystems

Giventhefollowingcontinuoussystem(differentialequation):

WewillusetheEulerforwardmethod:

Example:

Students:Findthediscretedifferentialequation(penandpaper)andthensimulatethesysteminMATLAB,i.e.,plottheStepResponseofthesystem.Tip!Useaforloop

WhereumaybetheControlSignalfrome.g.,aPIDController

DiscreteSystemsSolution:

Giventhefollowingcontinuoussystem:

WewillusetheEulerforwardmethod:

DiscreteSystemsSolution:

% Simulation of discrete modelclear, clc, close all

% Model Parametersa = 0.25;b = 2;

% Simulation ParametersTs = 0.1; %sTstop = 20; %suk = 1; % Step in ux(1) = 0; % Initial value

% Simulationfor k=1:(Tstop/Ts)

x(k+1) = (1-a*Ts).*x(k) + Ts*b*uk;end

% Plot the Simulation Resultsk=0:Ts:Tstop;plot(k, x)grid on

MATLABCode:

Students:Trythisexample

Students:Analternativesolutionistousethebuilt-infunctionc2d() (convertfromcontinoustodiscrete).Trythisfunctionandseeifyougetthesameresults.

DiscreteSystemsSolution:

% Find Discrete modelclear, clc, close all

% Model Parametersa = 0.25;b = 2;Ts = 0.1; %s

% State-space modelA = [-a];B = [b];C = [1];D = [0];

model = ss(A,B,C,D)model_discrete = c2d(model, Ts, 'forward')step(model_discrete)grid on

MATLABCode:

Students:Trythisexample

EulerForwardmethod

Whatsnext?

Self-pacedTutorialswithlotsofExercisesandVideoresources

DoasmanyExercisesaspossible! TheonlywaytolearnMATLABisbydoingExercisesandhands-onCoding!!!

LearningbyDoing!

Lesson 3

• Interpolation• CurveFitting

Interpolationx y

0 15

1 10

2 9

3 6

4 2

5 0

GiventhefollowingDataPoints:

Problem:Wewanttofindtheinterpolatedvaluefor,e.g.,𝑥 = 3.5

Example

Students:Trythisexample

x=0:5;y=[15, 10, 9, 6, 2, 0];

plot(x,y ,'o')grid

(LoggedDatafromagivenProcess)

Interpolation

x=0:5;y=[15, 10, 9, 6, 2, 0];

plot(x,y ,'-o')grid on

new_x=3.5;new_y = interp1(x,y,new_x)

new_y =

4

Wecanuseoneofthebuilt-inInterpolationfunctionsinMATLAB:

MATLABgivesustheanswer4.Fromtheplotweseethisisagoodguess:

Students:Trythisexample

CurveFitting

• Intheprevioussectionwefoundinterpolatedpoints,i.e.,wefoundvaluesbetweenthemeasuredpointsusingtheinterpolationtechnique.

• Itwouldbemoreconvenienttomodelthedataasamathematicalfunction𝑦 = 𝑓(𝑥).

• Thenwecan easilycalculateanydatawewantbasedonthismodel.

DataMathematicalModel

CurveFitting LinearRegression

x y

0 15

1 10

2 9

3 6

4 2

5 0

GiventhefollowingDataPoints:

Example:

x=0:5;y=[15, 10, 9, 6, 2, 0];

plot(x,y ,'o')grid

Basedontheplotweassumealinearrelationship:

WewilluseMATLABinordertofindaandb.

BasedontheDataPointswecreateaPlotinMATLAB

Students:Trythisexample

CurveFitting LinearRegressionExample

Basedontheplotweassumealinearrelationship:

WewilluseMATLABinordertofindaandb.

clearclc

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

p =

-2.9143 14.2857

Next:WewillthenplotandvalidatetheresultsinMATLAB

Students:Trythisexample

CurveFitting LinearRegressionExample

clearclcclose all

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

a=p(1);b=p(2);

ymodel = a*x+b;

plot(x,y,'o',x,ymodel)Students:Trythisexample

WewillplotandvalidatetheresultsinMATLAB

x y

0 15

1 10

2 9

3 6

4 2

5 0

Weseethisgivesagoodmodelbasedonthedataavailable.

CurveFitting LinearRegression

Students:Trythisexample

Problem:Wewanttofindtheinterpolatedvaluefor,e.g.,x=3.5

3waystodothis:• Usetheinterp1 function (shownearlier)• Implementy=-2.9+14.3 andcalculatey(3.5)• Usethepolyval function

x y

0 15

1 10

2 9

3 6

4 2

5 0

... (see previus examples)

new_x=3.5;

new_y = interp1(x,y,new_x)

new_y = a*new_x + b

new_y = polyval(p, new_x)

CurveFitting PolynomialRegression

Students:Trytofindmodelsbasedonthegivendatausingdifferentorders(1.order– 6.ordermodels).Plotthedifferentmodelsinasubplotforeasycomparison.

1.order:

2.order:

3.order:

etc.

p = polyfit(x,y,1)

x y

0 15

1 10

2 9

3 6

4 2

5 0

p = polyfit(x,y,2)

p = polyfit(x,y,3)

clearclcclose all

x=[0, 1, 2, 3, 4 ,5];y=[15, 10, 9, 6, 2 ,0];

for n=1:6 % n = model order

p = polyfit(x,y,n)

ymodel = polyval(p,x);

subplot(3,2,n)plot(x,y,'o',x,ymodel)title(sprintf('Model order %d', n));

end

CurveFitting

• Asexpected,thehigherordermodelsmatchthedatabetterandbetter.

• Note!Thefifthordermodelmatchesexactlybecausetherewereonlysixdatapointsavailable.

• n>5makesnosensebecausewehaveonly6datapoints

Whatsnext?

Self-pacedTutorialswithlotsofExercisesandVideoresources

DoasmanyExercisesaspossible! TheonlywaytolearnMATLABisbydoingExercisesandhands-onCoding!!!

LearningbyDoing!

Lesson 4

• NumericalDifferentiation• NumericalIntegration

NumericalDifferentiation

Anumericalapproachtothederivativeofafunctiony=f(x)is:

Note!WewilluseMATLABinordertofindthenumeric solution– nottheanalyticsolution

NumericalDifferentiationExample:

Weknowforthissimpleexamplethattheexactanalyticalsolutionis:

Giventhefollowingvalues:x y

-2 4

-1 1

0 0

1 1

2 4

NumericalDifferentiationExample:

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

% Exact Solutiondydx_exact = 2*x;

% Numerical Solutiondydx_num = diff(y)./diff(x);

% Compare the Resultsdydx = [[dydx_num, NaN]', dydx_exact']plot(x,[dydx_num, NaN]', x, dydx_exact')

Students:Trythisexample.Tryalsotoincreasenumberofdatapoints,x=-2:0.1:2

dydx =

-3 -4-1 -21 03 2

NaN 4

ExactSolution

NumericalSolution

numeric

exact

NumericalDifferentiation

x=-2:2

x=-2:0.1:2

Theresultsbecomemoreaccuratewhenincreasingnumberofdatapoints

NumericalIntegration

Anintegralcanbeseenastheareaunderacurve.Giveny=f(x) theapproximationoftheArea(A)underthecurvecanbefounddividingtheareaupintorectanglesandthensummingthecontributionfromalltherectangles(trapezoidrule):

NumericalIntegrationExample:Weknowthattheexactsolutionis:

x=0:0.1:1;y=x.^2;plot(x,y)

% Calculate the Integral:avg_y=y(1:length(x)-1)+diff(y)/2;A=sum(diff(x).*avg_y)

WeuseMATLAB(trapezoidrule):

A = 0.3350Students:Trythisexample

NumericalIntegrationExample:Weknowthattheexactsolutionis:

clearclcclose all

x=0:0.1:1;y=x.^2;

plot(x,y)

% Calculate the Integral (Trapezoid method):avg_y = y(1:length(x)-1) + diff(y)/2;A = sum(diff(x).*avg_y)

% Calculate the Integral (Simpson method):A = quad('x.^2', 0,1)

% Calculate the Integral (Lobatto method):A = quadl('x.^2', 0,1)

Students:Trythisexample.Comparetheresults.Which givesthebestmethod?

InMATLABwehaveseveralbuilt-infunctionswecanusefornumericalintegration:

Whatsnext?

Self-pacedTutorialswithlotsofExercisesandVideoresources

DoasmanyExercisesaspossible! TheonlywaytolearnMATLABisbydoingExercisesandhands-onCoding!!!

LearningbyDoing!

Lesson 5

• Optimization

OptimizationOptimizationisimportantinmodelling,controlandsimulationapplications.Optimizationisbasedonfindingtheminimumofagivencriteriafunction.

WewanttofindforwhatvalueofxthefunctionhasitsminimumvalueExample:

clearclc

x = -20:0.1:20;y = 2.*x.^2 + 20.*x - 22;plot(x,y)grid

i=1;while ( y(i) > y(i+1) )

i = i + 1; end

x(i)y(i)

Students:Trythisexample

Theminimumofthefunction

(-5,72)

OptimizationExample:

clearclcclose all

x = -20:1:20;f = mysimplefunc(x);plot(x, f)grid

x_min = fminbnd(@mysimplefunc, -20, 20)

y = mysimplefunc(x_min)

Students:Trythisexample

function f = mysimplefunc(x)

f = 2*x.^2 + 20.*x -22;

x_min =

-5

y =

-72

Note!ifwehavemorethan1variable,wehavetousee.g.,thefminsearch function

Wegotthesameresultsaspreviousslide

Whatsnext?

Self-pacedTutorialswithlotsofExercisesandVideoresources

DoasmanyExercisesaspossible! TheonlywaytolearnMATLABisbydoingExercisesandhands-onCoding!!!

LearningbyDoing!

Lesson 6

• TransferFunctions• State-spacemodels

Transferfunctions

TransferFunctions

DifferentialEquations

Laplace

H(s)

Example:

Input Output

Numerator

Denumerator

ATransferfunctionistheratiobetweentheinputandtheoutputofadynamicsystemwhenalltheothersinputvariablesandinitialconditionsissettozero

Transferfunctions

1.orderTransferfunction:

StepResponse:

1.orderTransferfunctionwithTimeDelay:

TransferfunctionsExample:

clearclcclose all

% Transfer Functionnum = [4];den = [2, 1];H = tf(num, den)

% Step Responsestep(H)

MATLAB:

Students:Trythisexample

Transferfunctions2.orderTransferfunction:

Example:

clearclcclose all

% Transfer Functionnum = [2];den = [1, 4, 3];H = tf(num, den)

% Step Responsestep(H)

Students:Trythisexample.TrywithdifferentvaluesforK,a,b andc.

MATLAB:

State-spacemodelsAsetwithlineardifferentialequations:

Canbestructuredlikethis:

Whichcanbestatedonthefollowingcompactform:

State-spacemodelsExample:

clearclcclose all

% State-space modelA = [1, 2; 3, 4];B = [0; 1];

C = [1, 0];D = [0];

ssmodel = ss(A, B, C, D)

% Step Responsestep(ssmodel)

% Transfer functionH = tf(ssmodel)

Students:Trythisexample

MATLAB:Note!Thesystemisunstable

Mass-Spring-DamperSystem

Example:

State-spacemodels

Students:FindtheState-spacemodelandfindthestepresponseinMATLAB.Trywithdifferentvaluesfork,m,candF.Discusstheresults

Mass-Spring-DamperSystemState-spacemodelsWeset: Thisgives:

Finally:

Thisgives:

Note!wehavesetF=u

k = 5;c = 1;m = 1;

A = [0 1; -k/m -c/m];B = [0; 1/m];C = [0 1];D = [0];sys = ss(A, B, C, D)

step(sys)

Whatsnext?

Self-pacedTutorialswithlotsofExercisesandVideoresources

DoasmanyExercisesaspossible! TheonlywaytolearnMATLABisbydoingExercisesandhands-onCoding!!!

LearningbyDoing!

Lesson 7

• FrequencyResponse

FrequencyResponse

DynamicSystem

Imput SignalOutputSignal

Gain PhaseLag

AirHeater

FrequencyAmplitude

Thefrequencyresponseofasystemexpresseshowasinusoidalsignalofagivenfrequencyonthesysteminputistransferredthroughthesystem.

Example:

FrequencyResponse- Definition

• Thefrequencyresponseofasystemisdefinedasthesteady-state responseofthesystemtoasinusoidalinputsignal.

• Whenthesystemisinsteady-state,itdiffersfromtheinputsignalonlyinamplitude/gain(A)(“forsterkning”)andphaselag(ϕ)(“faseforskyvning”).

andthesameforFrequency3,4,5,6,etc.

FrequencyResponseExample:

clearclcclose all

% Define Transfer functionnum=[1];den=[1, 1];H = tf(num, den)

% Frequency Responsebode(H);grid on Thefrequencyresponseisanimportanttoolforanalysisanddesign

ofsignalfiltersandforanalysisanddesignofcontrolsystems.

Students:TrythisExample

Whatsnext?

Self-pacedTutorialswithlotsofExercisesandVideoresources

DoasmanyExercisesaspossible! TheonlywaytolearnMATLABisbydoingExercisesandhands-onCoding!!!

LearningbyDoing!

Hans-PetterHalvorsen,M.Sc.

UniversityCollegeofSoutheastNorwaywww.usn.no

E-mail:hans.p.halvorsen@hit.noBlog:http://home.hit.no/~hansha/