-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_exampleSimulation.m
More file actions
executable file
·97 lines (75 loc) · 2.53 KB
/
Copy pathmain_exampleSimulation.m
File metadata and controls
executable file
·97 lines (75 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
clc
close all
% bdclose all
clear all
addpath('Sources')
%% Step 0: Load Current Execise Data
% (needed to run the simulation)
currentExercise=1;
% Possible simplifications (activate by setting the variable to 1):
removeContraints=1;
removeDistrubance=0;
exerciseData=LoadMPCExercise(currentExercise,removeContraints,removeDistrubance);
% Relavant data for the controller design
exerciseData.u_max;
exerciseData.u_min;
%% MPC controller design %%
%% Step 1: upload a model of the system to be controlled
% Possible simplifications (activate by setting the variable to 1):
exactModel=1;
SystemModel=LoadSystemModel(currentExercise,exactModel);
%% Step 2: use to model to create the condensed MPC matrices
Q = [[500]];
R = [[1]];
S = [[0]];
F = [1 -1];
f = [exerciseData.u_max; exerciseData.u_max];
N = 10; % prediction horizon
T = 500; % simulation time
td = 0:exerciseData.Ts:T; % time vector
cUr = zeros(1, N); % reference input
% Disturbance
dstrb = exerciseData.D;
start_dstrb = exerciseData.Tdist;
ds = dstrb .* heaviside(td - start_dstrb); % vector of disturbances
% You are provided with the command
cm=BuildCondensedMPCmatrices(SystemModel,R,Q,F,f,N,S); % Warning: this command will produce an error, since R,Q,F,f and PH are currently undefined.
%% Option 2: Using a matlab for cycle:
% Initalization
x_k=zeros(size(exerciseData.System.A,1),1);
u_memory=0;
x_memory=x_k;
y_memory=exerciseData.System.C*x_k;
% Basic Closed-Loop system simulation
for k=exerciseData.Ts:exerciseData.Ts:exerciseData.SimTime
% Compute the the control action to be used using MPC
u_k=1000; % in this example always u=1
H_qp = cm.cBC'*cm.cQ*cm.cBC + cm.cR;
% f_hq = ((cm.cAC * x_k + cm.cM * )' )';
% Simulate Plant Response
x_kplus1=exerciseData.System.A*x_k+exerciseData.System.B*u_k;
y=exerciseData.System.C*x_k %+exerciseData.System.D*u_k;
% Save for plots
u_memory(:,end+1)=u_k;
x_memory(:,end+1)=x_k;
y_memory(:,end+1)=y;
% Update and repeat
x_k=x_kplus1;
end
% Basic Plot
figure
subplot(2,1,1)
plot(0:exerciseData.Ts:exerciseData.SimTime,y_memory)
xlabel('Time [s]')
if currentExercise==1
ylabel('Speed [km/h]')
elseif currentExercise==3
ylabel('Position [m]')
end
title('System Output')
subplot(2,1,2)
plot(0:exerciseData.Ts:exerciseData.SimTime,u_memory)
xlabel('Time [s]')
ylabel('Force [m]')
title('Control Action')
%------------%