%% Analyze Closed-Loop Response
% Perform closed-loop simulation of a plant with one MV and one measured OV.
% Define a plant model and create a model predictive controller with MV constraints.

ts = 2;
Plant = ss(0.8,0.5,0.25,0,ts);
MPCobj = mpc(Plant);
MPCobj.MV(1).Min = -2;
MPCobj.MV(1).Max = 2;

%
% Initialize an mpcstate object for simulation. Use the default state properties.

x = mpcstate(MPCobj);

%
% Set the reference signal. There is no measured disturbance.

r = 1;

%
% Simulate the closed-loop response by calling mpcmove iteratively.

t = [0:ts:40];
N = length(t);
y = zeros(N,1); 
u = zeros(N,1); 
for i = 1:N
    % simulated plant and predictive model are identical
    y(i) = 0.25*x.Plant;
    u(i) = mpcmove(MPCobj,x,y(i),r);
end

% y and u store the OV and MV values.
%
% Analyze the result.

[ts,us] = stairs(t,u);
plot(ts,us,'r-',t,y,'b--')
legend('MV','OV')

%
% Modify the MV upper bound as the simulation proceeds using an mpcmoveopt object.

MPCopt = mpcmoveopt;
MPCopt.MVMin = -2;
MPCopt.MVMax = 2;

%
% Simulate the closed-loop response and introduce the real-time upper limit change at eight seconds (the fifth iteration step).

x = mpcstate(MPCobj);
y = zeros(N,1);
u = zeros(N,1);
for i = 1:N
    % simulated plant and predictive model are identical
    y(i) = 0.25*x.Plant;
    if i == 5
    	MPCopt.MVMax = 1;
    end
    u(i) = mpcmove(MPCobj,x,y(i),r,[],MPCopt);
end

%
% Analyze the result.

[ts,us] = stairs(t,u);
plot(ts,us,'r-',t,y,'b--')
legend('MV','OV')

% Copyright 2015 The MathWorks, Inc.