%% Worst-Case Gain at Frequencies in a Range
% Consider a model of a control system containing uncertain elements.

k = ureal('k',10,'Percent',40);
delta = ultidyn('delta',[1 1]); 
G = tf(18,[1 1.8 k]) * (1 + 0.5*delta);
C = pid(2.3,3,0.38,0.001);
CL = feedback(G*C,1);

%
% By default, wcgain returns only the worst-case peak gain over all frequencies. To obtain worst-case gain values at multiple frequencies, use the 'VaryFrequency' option of wcOptions. For example, compute the highest possible gain of the system at frequency points between 0.1 and 10 rad/s.

opts = wcOptions('VaryFrequency','on');
[wcg1,wcu1,info1] = wcgain(CL,{0.1,10},opts);
info1

%
% wcgain returns the vector of frequencies in the info output, in the Frequencies field. info.Bounds contains the upper and lower bounds on the worst-case gain at each frequency. Use these values to plot the frequency dependence of the worst-case gain.

semilogx(info1.Frequency,info1.Bounds)
title('Worst-Case Gain vs. Frequency')
ylabel('Gain')
xlabel('Frequency')
legend('Lower bound','Upper bound','Location','northwest')

% The curve shows the high-gain envelope for all systems within the uncertainty ranges of CL. You can also use wcsigmaplot to plot this envelope along with samples of the system.
%
% When you use the 'VaryFrequency' option, wcgain chooses frequency points automatically. The frequencies it selects are guaranteed to include the frequency at which the worst-case gain is highest (within the specified range). Display the returned frequency values to confirm that they include the critical frequency.

info1.Frequency
wcg1.CriticalFrequency

%
% Alternatively, instead of using 'VaryFrequency', you can specify particular frequencies at which to compute the worst-case gains. info.Bounds contains the worst-case gains at all specified frequencies.

w = logspace(-1,1,24); 
[wcg2,wcu2,info2] = wcgain(CL,w);
semilogx(w,info2.Bounds)
title('Worst-Case Gain vs. Frequency')
ylabel('Gain')
xlabel('Frequency')
legend('Lower bound','Upper bound','Location','northwest')

%
% When you provide the frequency grid in this way, the results are not guaranteed to include the overall worst-case gain, which might fall between specified frequency points. To see this, examine wcg1 and wcg2, which contain the bounds for the two approaches.

wcg1

%

wcg2

% wcg1, computed using VaryFrequency, finds a higher peak gain than the specified frequency grid.
%
% Copyright 2012 The MathWorks, Inc.