%% Robust Stability Margin 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 transfer function.

C = pid(2.3,3,0.38,0.001);
CL = feedback(G*C,1);

%
% A step response plot shows that the closed-loop system is nominally stable.

step(CL.NominalValue)

%
% Examine the robust stability of the closed-loop system.

[stabmarg,wcu] = robstab(CL);
stabmarg

% The LowerBound and UpperBound fields of stabmarg show the robust stability margin of the closed-loop system is around 1.6. This result means that the system can withstand about 60% more uncertainty than is specified in the uncertain elements without going unstable.
% You can use uscale to scale system uncertainty by the stability margin, to examine the system response for the full range of safe uncertainties. Scale the uncertainties in CL by the robust stability margin to create a system with the maximum tolerable amount of uncertainty.

CLmaxunc = uscale(CL,stabmarg.UpperBound);
CLmaxunc.Uncertainty.delta
CLmaxunc.Uncertainty.k

% The uncertain elements in CLmaxunc have ranges about 1.6 times the range of the original modeled uncertainty in CL.
%
% The output wcu is a structure that contains the smallest perturbation to k and delta that make the system unstable. Confirm the instability by substituting these values into the closed-loop model and examining the pole locations.

CLunst = usubs(CL,wcu);
pole(CLunst)

% The resulting system has an undamped pair of complex poles with natural frequency 4.89, which renders it unstable. The CriticalFrequency field of stabmarg contains the same value, which is the frequency at which the CL is closest to instability.
%
% Copyright 2012 The MathWorks, Inc.