! Closed-loop simulations
MPT3 introduces a special object to represent closed-loop systems, consisting of a [[UI.Systems|dynamical system]] and an [[UI.Control|MPC controller]]:
(:source lang=MATLAB -getcode:) [@
loop = ClosedLoop(mpc, sys)
@]
where @@mpc@@ represents an MPC controller (either on-line or explicit MPC), and @@sys@@ describes the dynamical system.
After a closed-loop object is constructed, you can simulate it by
(:source lang=MATLAB -getcode:) [@
data = loop.simulate(x0, Nsim)
@]
where @@x0@@ is the initial state for the simulation, and @@Nsim@@ is the number of simulation steps.
As an example, consider MPC for a linear system @@x^+ = A x + B u@@ with following properties:
* @@A = [1 1; 0 1]@@, @@B = [1; 0.5]@@
* state constraints @@[-5; -5] <= x <= [5; 5]@@
* input constraints @@-1 <= x <= 1@@
* prediction horizon 4
* quadratic cost function with unity weighting matrices
(:source lang=MATLAB -getcode:) [@
prediction_model = LTISystem('A', [1 1; 0 1], 'B', [1; 0.5]);
prediction_model.x.min = [-5; -5];
prediction_model.x.max = [5; 5];
prediction_model.u.min = -1;
prediction_model.u.max = 1;
prediction_model.x.penalty = Penalty([1 0; 0 1], 2);
prediction_model.u.penalty = Penalty(1, 2);
N = 4;
mpc = MPCController(prediction_model, N);
@]
Now we want to verify how the controller performs if connected to a different system, say @@x^+ = A x + B u@@ with @@A = [1 1; 0.2 1]@@, @@B = [1; 0.8]@@:
(:source lang=MATLAB -getcode:) [@
simulation_model = LTISystem('A', [1 1; 0.2 1], 'B', [1; 0.8]);
loop = ClosedLoop(mpc, simulation_model);
x0 = [4; 0];
Nsim = 20;
data = loop.simulate(x0, Nsim)
data =
X: [2x21 double]
U: [1x20 double]
Y: []
cost: [1x20 double]
plot(data.X')
@]
*NOTE:* if you change the controller and/or the system in your MATLAB workspace, the change(s) will be *automatically* propagate to the closed-loop object without the need to re-create it. In other words, in the example above we can as well do:
(:source lang=MATLAB -getcode:) [@
mpc.N = 10;
data = loop.simulate(x0, Nsim)
@]
and the simulation will automatically use the new controller with prediction horizon @@10@@.