Modelling and Simulation in MATLAB

advertisement
QuickStartTutorial
Modelling,Simulation&Control
Hans-PetterHalvorsen,M.Sc.
WhatisMATLAB?
• MATLABisatoolfortechnicalcomputing,computationand
visualizationinanintegratedenvironment.
• MATLABisanabbreviationforMATrixLABoratory
• ItiswellsuitedforMatrix manipulationandproblemsolving
relatedtoLinearAlgebra,Modelling,SimulationandControl
Applications
• PopularinUniversities, TeachingandResearch
Lessons
1.
2.
3.
4.
5.
6.
7.
SolvingDifferentialEquations(ODEs)
DiscreteSystems
Interpolation/CurveFitting
NumericalDifferentiation/Integration
Optimization
TransferFunctions/State-spaceModels
FrequencyResponse
Lesson1
Solving ODEsinMATLAB
- OrdinaryDifferentialEquations
Example:
Where
DifferentialEquations
Note!
TistheTimeconstant
TheSolutioncanbeprovedtobe(willnotbeshownhere):
T = 5;
a = -1/T;
x0 = 1;
t = [0:1:25];
x = exp(a*t)*x0;
Usethefollowing:
plot(t,x);
grid
Students:Trythisexample
DifferentialEquations
Problemwiththismethod:
WeneedtosolvetheODEbeforewecanplotit!!
T = 5;
a = -1/T;
x0 = 1;
t = [0:1:25];
x = exp(a*t)*x0;
plot(t,x);
grid
UsingODESolversinMATLAB
Example:
Step1:DefinethedifferentialequationasaMATLABfunction(mydiff.m):
function dx = mydiff(t,x)
T = 5;
a = -1/T;
dx = a*x;
x0
Step2:Useoneofthebuilt-inODEsolver(ode23,
ode45,...)inaScript.
clear
clc
tspan = [0 25];
x0 = 1;
tspan
[t,x] = ode23(@mydiff,tspan,x0);
plot(t,x)
Students:Trythisexample.Doyougetthesameresult?
HigherOrderODEs
Mass-Spring-DamperSystem
Example(2.orderdifferentialequation):
InordertousetheODEsinMATLABweneedreformulateahigher
ordersystemintoasystemoffirstorderdifferentialequations
HigherOrderODEs
Mass-Spring-DamperSystem:
InordertousetheODEsinMATLABweneedreformulateahigher
ordersystemintoasystemoffirstorderdifferentialequations
Weset:
Thisgives:
Finally:
NowwearereadytosolvethesystemusingMATLAB
Step1:DefinethedifferentialequationasaMATLABfunction
(mass_spring_damper_diff.m):
function dx = mass_spring_damper_diff(t,x)
k
m
c
F
=
=
=
=
1;
5;
1;
1;
Students:Trywithdifferent
valuesfork,m,candF
Students:Trythisexample
dx = zeros(2,1); %Initialization
dx(1) = x(2);
dx(2) = -(k/m)*x(1)-(c/m)*x(2)+(1/m)*F;
Step2:Usethebuilt-in
ODEsolverinascript.
clear
clc
tspan = [0 50];
x0 = [0;0];
[t,x] = ode23(@mass_spring_damper_diff,tspan,x0);
plot(t,x)
...
[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))
Forgreaterflexibilitywewanttobeabletochangetheparameters
k,m,c,andFwithoutchangingthefunction,onlychangingthe
script.Abetterapproachwouldbetopasstheseparameterstothe
functioninstead.
Step1:DefinethedifferentialequationasaMATLABfunction
(mass_spring_damper_diff.m):
function dx = mass_spring_damper_diff(t,x, param)
k
m
c
F
=
=
=
=
param(1);
param(2);
param(3);
param(4);
dx = zeros(2,1);
dx(1) = x(2);
dx(2) = -(k/m)*x(1) - (c/m)*x(2) + (1/m)*F;
Students:Trythisexample
Step2:Usethebuilt-inODEsolverinascript:
clear
clc
close 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)
Students:Trythisexample
Whatsnext?
LearningbyDoing!
Self-pacedTutorialswithlotsof
ExercisesandVideoresources
DoasmanyExercisesaspossible! Theonlywaytolearn
MATLABisbydoingExercisesandhands-onCoding!!!
Lesson 2
• DiscreteSystems
DiscreteSystems
• Whendealingwithcomputersimulations,weneedtocreatea
discreteversionofoursystem.
• Thismeansweneedtomakeadiscreteversionofourcontinuous
differentialequations.
• Actually,thebuilt-inODEsolversinMATLABusedifferent
discretizationmethods
• Interpolation,CurveFitting,etc.isalsobasedonasetofdiscrete
values(datapointsormeasurements)
• ThesamewithNumericalDifferentiationandNumerical
Integration
Discretevalues
• etc.
x
y
0
15
1
10
2
9
3
6
4
2
5
0
DiscreteSystems
DiscreteApproximationofthetimederivative
Eulerbackwardmethod:
Eulerforwardmethod:
DiscreteSystems
Eulerbackwardmethod:
DiscretizationMethods
MoreAccurate!
Eulerforwardmethod:
OthermethodsareZeroOrderHold(ZOH),Tustin’smethod,etc.
Simplertouse!
DiscreteSystems
DifferentDiscreteSymbolsandmeanings
Previous Value:
Present Value:
Next (Future)Value:
Note!DifferentNotationisusedindifferentlitterature!
Example:
DiscreteSystems
Giventhefollowingcontinuoussystem(differentialequation):
Whereu maybetheControlSignalfrome.g.,aPIDController
WewillusetheEulerforwardmethod:
Students:Findthediscretedifferentialequation(penandpaper)andthen
simulatethesysteminMATLAB,i.e.,plottheStepResponseofthesystem.
Tip!Useaforloop
Solution:
DiscreteSystems
Giventhefollowingcontinuoussystem:
WewillusetheEulerforwardmethod:
Solution:
DiscreteSystems
Students:Trythisexample
MATLABCode:
% Simulation of discrete model
clear, clc, close all
% Model Parameters
a = 0.25;b = 2;
% Simulation Parameters
Ts = 0.1; %s
Tstop = 20; %s
uk = 1; % Step in u
x(1) = 0; % Initial value
% 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
Students:Analternativesolutionistousethebuilt-in
functionc2d() (convertfromcontinoustodiscrete).
Trythisfunctionandseeifyougetthesameresults.
Solution:
DiscreteSystems
MATLABCode:
% Find Discrete model
clear, clc, close all
% Model Parameters
a = 0.25;
b = 2;
Ts = 0.1; %s
%
A
B
C
D
State-space model
= [-a];
= [b];
= [1];
= [0];
model = ss(A,B,C,D)
model_discrete = c2d(model, Ts, 'forward')
step(model_discrete)
grid on
EulerForwardmethod
Students:Trythisexample
Whatsnext?
LearningbyDoing!
Self-pacedTutorialswithlotsof
ExercisesandVideoresources
DoasmanyExercisesaspossible! Theonlywaytolearn
MATLABisbydoingExercisesandhands-onCoding!!!
Lesson 3
• Interpolation
• CurveFitting
Example
Interpolation
GiventhefollowingDataPoints:
x
y
0
15
1
10
2
9
3
6
4
2
5
0
(Logged
Datafrom
agiven
Process)
x=0:5;
y=[15, 10, 9, 6, 2, 0];
plot(x,y ,'o')
grid
Students:Trythisexample
Problem:Wewanttofindtheinterpolatedvaluefor,e.g.,𝑥 = 3.5
Interpolation
Wecanuseoneofthebuilt-inInterpolationfunctionsinMATLAB:
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)
MATLABgivesustheanswer4.
Fromtheplotweseethisisagoodguess:
Students:Trythisexample
new_y =
4
CurveFitting
• Intheprevioussectionwefoundinterpolatedpoints,i.e.,wefoundvalues
betweenthemeasuredpointsusingtheinterpolationtechnique.
• Itwouldbemoreconvenienttomodelthedataasamathematicalfunction
𝑦 = 𝑓(𝑥).
• Thenwecan easilycalculateanydatawewantbasedonthismodel.
Data
MathematicalModel
CurveFitting
Example:
LinearRegression
GiventhefollowingDataPoints:
x
y
0
15
1
10
2
9
3
6
4
2
5
0
Basedonthe
DataPointswe
createaPlotin
MATLAB
x=0:5;
y=[15, 10, 9, 6, 2, 0];
Basedontheplotweassumealinearrelationship:
plot(x,y ,'o')
grid
Students:Trythisexample
WewilluseMATLABinordertofindaandb.
CurveFitting
Example
LinearRegression
Basedontheplotweassumealinearrelationship:
WewilluseMATLABinordertofindaandb.
Students:Trythisexample
clear
clc
x=[0, 1, 2, 3, 4 ,5];
y=[15, 10, 9, 6, 2 ,0];
n=1; % 1.order polynomial
p = polyfit(x,y,n)
Next:Wewillthenplotand
validatetheresultsinMATLAB
p =
-2.9143
14.2857
Example
CurveFitting
LinearRegression
Wewillplotandvalidate
theresultsinMATLAB
clear
clc
close all
x
0
15
1
10
2
9
3
6
4
2
5
0
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)
y
Weseethisgivesagood
modelbasedonthedata
available.
Students:Trythisexample
x
y
0
15
1
10
2
9
3
6
4
2
5
0
CurveFitting
LinearRegression
Problem:Wewanttofindtheinterpolatedvaluefor,e.g.,x=3.5
... (see previus examples)
3waystodothis:
• Usetheinterp1 function (shownearlier)
• Implementy=-2.9+14.3 andcalculatey(3.5)
• Usethepolyval function
new_x=3.5;
new_y = interp1(x,y,new_x)
new_y = a*new_x + b
new_y = polyval(p, new_x)
Students:Trythisexample
CurveFitting
PolynomialRegression
1.order:
p = polyfit(x,y,1)
2.order:
p = polyfit(x,y,2)
3.order:
p = polyfit(x,y,3)
etc.
Students:Trytofindmodelsbasedonthegivendatausing
differentorders(1.order– 6.ordermodels).
Plotthedifferentmodelsinasubplotforeasycomparison.
x
y
0
15
1
10
2
9
3
6
4
2
5
0
CurveFitting
clear
clc
close 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
• Asexpected,thehigherordermodelsmatchthedata
betterandbetter.
• Note!Thefifthordermodelmatchesexactlybecausethere
wereonlysixdatapointsavailable.
• n>5makesnosensebecausewehaveonly6datapoints
Whatsnext?
LearningbyDoing!
Self-pacedTutorialswithlotsof
ExercisesandVideoresources
DoasmanyExercisesaspossible! Theonlywaytolearn
MATLABisbydoingExercisesandhands-onCoding!!!
Lesson 4
• NumericalDifferentiation
• NumericalIntegration
NumericalDifferentiation
Anumericalapproachtothederivativeofafunctiony=f(x)is:
Note!WewilluseMATLABinordertofindthenumeric solution– nottheanalyticsolution
NumericalDifferentiation
Example:
Weknowforthissimpleexample
thattheexactanalyticalsolutionis:
Giventhefollowingvalues:
x
-2
-1
0
y
4
1
0
1
2
1
4
Example:
NumericalDifferentiation
MATLABCode:
x=-2:2;
y=x.^2;
% Exact Solution
dydx_exact = 2*x;
numeric
exact
% Numerical Solution
dydx_num = diff(y)./diff(x);
Numerical
Exact
Solution
Solution
% Compare the Results
dydx = [[dydx_num, NaN]', dydx_exact']
plot(x,[dydx_num, NaN]', x, dydx_exact')
dydx =
Students:Trythisexample.
Tryalsotoincreasenumberofdatapoints,x=-2:0.1:2
-3
-1
1
3
NaN
-4
-2
0
2
4
NumericalDifferentiation
x=-2:0.1:2
x=-2:2
Theresultsbecomemore
accuratewhenincreasing
numberofdatapoints
NumericalIntegration
Anintegralcanbeseenastheareaunderacurve.
Giveny=f(x) theapproximationoftheArea(A)underthecurvecanbefounddividingtheareaupinto
rectanglesandthensummingthecontributionfromalltherectangles(trapezoidrule):
Example:
NumericalIntegration
Weknowthattheexactsolutionis:
WeuseMATLAB(trapezoidrule):
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)
A = 0.3350
Students:Trythisexample
Example:
NumericalIntegration
Weknowthattheexactsolutionis:
InMATLABwehaveseveralbuilt-infunctionswecanusefornumericalintegration:
clear
clc
close all
x=0:0.1:1;
y=x.^2;
Students:Trythisexample.
Comparetheresults.
Which givesthebestmethod?
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)
Whatsnext?
LearningbyDoing!
Self-pacedTutorialswithlotsof
ExercisesandVideoresources
DoasmanyExercisesaspossible! Theonlywaytolearn
MATLABisbydoingExercisesandhands-onCoding!!!
Lesson 5
• Optimization
Optimization
Optimizationisimportantinmodelling,controlandsimulationapplications.
Optimizationisbasedonfindingtheminimumofagivencriteriafunction.
Example:
Wewanttofindforwhatvalueofxthefunctionhasitsminimumvalue
clear
clc
Students:Trythisexample
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)
(-5,72)
Theminimumofthefunction
Optimization
Example:
Students:Trythisexample
function f = mysimplefunc(x)
f = 2*x.^2 + 20.*x -22;
x_min =
-5
Note!ifwehavemorethan1variable,wehave
tousee.g.,thefminsearch function
clear
clc
close all
x = -20:1:20;
f = mysimplefunc(x);
plot(x, f)
grid
y =
-72
Wegotthesameresultsaspreviousslide
x_min = fminbnd(@mysimplefunc, -20, 20)
y = mysimplefunc(x_min)
Whatsnext?
LearningbyDoing!
Self-pacedTutorialswithlotsof
ExercisesandVideoresources
DoasmanyExercisesaspossible! Theonlywaytolearn
MATLABisbydoingExercisesandhands-onCoding!!!
Lesson 6
• TransferFunctions
• State-spacemodels
Transferfunctions
Differential
Equations
H(s)
Input
Output
Laplace
Transfer
Functions
ATransferfunctionistheratiobetweentheinputandtheoutputofadynamic
systemwhenalltheothersinputvariablesandinitialconditionsissettozero
Numerator
Example:
Denumerator
Transferfunctions
1.orderTransferfunctionwithTimeDelay:
1.orderTransferfunction:
StepResponse:
Example:
Transferfunctions
MATLAB:
clear
clc
close all
% Transfer Function
num = [4];
den = [2, 1];
H = tf(num, den)
% Step Response
step(H)
Students:Trythisexample
Transferfunctions
2.orderTransferfunction:
MATLAB:
Example:
clear
clc
close all
% Transfer Function
num = [2];
den = [1, 4, 3];
H = tf(num, den)
% Step Response
step(H)
Students:Trythisexample.
TrywithdifferentvaluesforK,a,b andc.
State-spacemodels
Asetwithlineardifferentialequations:
Canbestructuredlikethis:
Whichcanbestatedonthe
followingcompactform:
Example:
State-spacemodels
MATLAB:
clear
clc
close all
% State-space model
A = [1, 2; 3, 4];
B = [0; 1];
C = [1, 0];
D = [0];
ssmodel = ss(A, B, C, D)
% Step Response
step(ssmodel)
% Transfer function
H = tf(ssmodel)
Students:Trythisexample
Note!The
systemis
unstable
State-spacemodels
Mass-Spring-DamperSystem
Example:
Students:FindtheState-spacemodelandfindthestepresponseinMATLAB.
Trywithdifferentvaluesfork,m,candF.
Discusstheresults
State-spacemodels
Thisgives:
Weset:
Finally:
Note!wehavesetF=u
k = 5;
c = 1;
m = 1;
A =
B =
C =
D =
sys
[0 1; -k/m -c/m];
[0; 1/m];
[0 1];
[0];
= ss(A, B, C, D)
step(sys)
Mass-Spring-DamperSystem
Thisgives:
Whatsnext?
LearningbyDoing!
Self-pacedTutorialswithlotsof
ExercisesandVideoresources
DoasmanyExercisesaspossible! Theonlywaytolearn
MATLABisbydoingExercisesandhands-onCoding!!!
Lesson 7
• FrequencyResponse
FrequencyResponse
Example:
AirHeater
Imput Signal
OutputSignal
Dynamic
System
Amplitude
Frequency
Gain
PhaseLag
Thefrequencyresponseofasystemexpresseshowasinusoidalsignalofagiven
frequencyonthesysteminputistransferredthroughthesystem.
FrequencyResponse- Definition
andthesameforFrequency3,4,5,6,etc.
•
•
Thefrequencyresponseofasystemisdefinedasthesteady-state responseofthesystemtoasinusoidal
inputsignal.
Whenthesystemisinsteady-state,itdiffersfromtheinputsignalonlyinamplitude/gain(A)
(“forsterkning”)andphaselag(ϕ)(“faseforskyvning”).
Example:
FrequencyResponse
clear
clc
close all
% Define Transfer function
num=[1];
den=[1, 1];
H = tf(num, den)
% Frequency Response
bode(H);
grid on
Students:TrythisExample
Thefrequencyresponseisanimportanttoolforanalysisanddesign
ofsignalfiltersandforanalysisanddesignofcontrolsystems.
Whatsnext?
LearningbyDoing!
Self-pacedTutorialswithlotsof
ExercisesandVideoresources
DoasmanyExercisesaspossible! Theonlywaytolearn
MATLABisbydoingExercisesandhands-onCoding!!!
Hans-PetterHalvorsen,M.Sc.
UniversityCollegeofSoutheastNorway
www.usn.no
E-mail:hans.p.halvorsen@hit.no
Blog:http://home.hit.no/~hansha/
Download