%% Robust Performance of Closed-Loop System
% Consider a control system whose plant contains both parametric uncertainty and dynamic uncertainty. Create a model of the plant using uncertain elements.

k = ureal('k',10,'Percent',40);
delta = ultidyn('delta',[1 1]); 
G = tf(18,[1 1.8 k]) * (1 + 0.5*delta);

%
% Create a model of the controller, and build the closed-loop sensitivity function, S. The sensitivity measures the closed-loop response at the plant output to a disturbance at the plant input.

C = pid(2.3,3,0.38,0.001);
S = feedback(1,G*C);
bodemag(S,S.NominalValue)

%
% The peak gain of the nominal response is very nearly 1, but some of the sampled systems within the uncertainty range exceed that level. Suppose that you can tolerate some ringdown in the response but do not want the peak gain to exceed 1.5. Use robgain to find out how much uncertainty the system can have while the peak gain remains below 1.5.

[perfmarg,wcu] = robgain(S,1.5);
perfmarg

%
% The LowerBound and UpperBound fields of perfmarg show that the robust performance margin is around 0.78. This result means that there is a perturbation of only about 78% of the uncertainty specified in S with peak gain exceeding 1.5.
% You can use uscale to examine what that normalized uncertainty of 78% means in terms of actual ranges of uncertainty. Scale all the uncertain elements in S to create a model of the closed-loop system with the maximum level of uncertainty that meets the performance requirement.

factor = perfmarg.LowerBound;
S_scaled = uscale(S,factor)

% The display shows how the uncertain elements in S_scaled have changed: the peak gain of the ultidyn element delta is reduced from 1 to 0.78, and the range of variation of the uncertain real parameter k is reduced from ±40% to ±31.3%.
%
% The output wcu is a structure that contains the perturbations to k and delta that correspond to the target maximum performance of 1.5. Verify that the values in wcu cause Smax to achieve the gain level of 1.5 by substituting them into S.

Smax = usubs(S,wcu);
getPeakGain(Smax,1e-6)

%
% Examine the disturbance rejection of the system with these values.

step(S.NominalValue,Smax)
legend('Nominal','Peak Gain = 1.5')

% The CriticalFrequency field of perfmarg contains the frequency at which the peak gain reaches 1.5.
% Copyright 2012 The MathWorks, Inc.