%% Design Controller for Identified Plant at the Command Line
% This example shows how to design a model predictive controller at the command line using an identified plant model.
% Load the input/output data.

load plantIO

% This command imports the plant input signal, u, plant output signal, y, and sample time, Ts, to the MATLAB® workspace.
%
% Create an iddata object from the input and output data.

mydata = iddata(y,u,Ts);

%
% Preprocess the I/O data by removing offsets (mean values) from the input and output signals.

mydatad = detrend(mydata);

% You can also remove offsets by creating an ssestOptions object and specifying the InputOffset and OutputOffset options.
%
% Estimate a second order, linear state-space model using the I/O data. Estimate a discrete-time model by specifying the sample time as Ts.

ss1 = ssest(mydatad,2,'Ts',Ts);

% The estimated model has one measured input and one unmeasured noise component.
%
% Create a default model predictive controller for the identified model, ss1.

mpcObj = mpc(ss1);

% By default the controller discards the unmeasured noise component from your identified model.
%
% To simplify the tuning process, specify input and output signal scaling factors.

mpcObj.MV(1).ScaleFactor = max(u) - min(u);
mpcObj.OV(1).ScaleFactor = max(y) - min(y);

%
% Specify the nominal values for the input and output signals. Use the offsets that you previously removed from the I/O data.

nominalInput = mean(u);
nominalOutput = mean(y);
mpcObj.Model.Nominal.u = nominalInput;
mpcObj.Model.Nominal.y = nominalOutput;

%
% Configure the simulation reference signal. Specify a reference signal with a five-second duration and a unit step at a time of one second. The initial value of the reference signal is the nominal value of the output signal.

outputRef = [nominalOutput*ones(1/Ts,1); 
             (nominalOutput+1)*ones(4/Ts+1,1)];

%
% Before tuning the controller, simulate the initial controller performance.

sim(mpcObj,[],outputRef)

% The default controller tracks the output reference value well, however the initial controller response is aggressive.
%
% To make the controller less aggressive, simultaneously increase the tuning weight for the manipulated variable rate of change and decrease the tuning weight for the output variable.

beta = 0.37;
mpcObj.Weights.MVRate = mpcObj.Weights.MVRate/beta;
mpcObj.Weights.OV = mpcObj.Weights.OV*beta;

%
% Simulate the tuned controller response

sim(mpcObj,[],outputRef)

% The input response is now more conservative. The trade-offs are an increased overshoot and longer settling time.
% Copyright 2012 The MathWorks, Inc.