%% Gain-Scheduled PID Controller
% This example shows how to create a gain-scheduled PID controller. The controller's proportional, integral, and derivative gains have linear, quadratic, and constant dependence on a scheduling variable, \alpha, as follows:
% \begin{array}{l}
% {k_p}\left( \alpha  \right) = {k_p}_0 + {k_{p1}}\alpha \\
% {k_i}\left( \alpha  \right) = {k_i}_0 + {k_{i1}}\alpha  + {k_{i2}}{\alpha ^2}\\
% {k_p}\left( \alpha  \right) = {k_d}_0.
% \end{array}
% For tuning purposes, sample these gain formulas for a number of values of \alpha that span the operating range of the scheduling variable. For example, sample the gain formulas for five values of \alpha (five design points) in [-1,1]. To do so, first create a vector of \alpha values.

alpha = -1:0.5:1;

%
% The PID gains depend on \alpha and \alpha^{2}. Evaluate these functions for the sampled values.

F1 = alpha;
F2 = alpha.^2;

%
% Create the tunable gain surfaces that represent the proportional, integral, and derivative gains over the grid of \alpha values. Initialize all the constant coefficients to 1.

Kp = gainsurf('Kp',1,F1);
Ki = gainsurf('Ki',1,F1,F2);
Kd = gainsurf('Kd',1);

% Each of Kp, Ki, and Kd is an array of generalized matrices. The array element Kp(:,:,1) (for example) corresponds to k_{p}(\alpha) for \alpha = -1. The element Kp(:,:,2) corresponds to k_{p}(\alpha) for \alpha = -0.5, and so on. These values depend on tunable coefficients Kp_0, and Kp_1. Thus, each of Kp, Ki, and Kd represents a gain curve in \alpha with the appropriate number of tunable coefficients.
%
% Combine the tunable gains into a PID controller. Set the derivative filter time constant to a fixed value of 0.1.

Tf = 0.1;
C = pid(Kp,Ki,Kd,Tf)

% You can use generalized matrices as arguments to model creation commands like pid and tf the same way you would use numeric arguments. The resulting controller is a generalized state-space (genss) model array that depends on the six coefficients of the gain curves. Each entry in the array is a PID controller evaluated at a particular value of \alpha.
%
% Associate the \alpha values with the corresponding entries of C.

SG = struct('alpha',alpha);
C.SamplingGrid = SG;

% Use model interconnection commands (such as connect and feedback) to combine C with an array of plant models sampled at the same values of \alpha. You can then use systune to tune the gain-scheduled controller to meet your design requirements.
% Copyright 2015 The MathWorks, Inc.