%% Robust Performance Margin as a Function of Frequency
% 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);
S = feedback(1,G*C);

%
% By default, robgain computes only the weakest performance margin over all frequencies. To see how the margin varies with frequency, use the 'VaryFrequency' option of robOptions. For example, compute the performance margin of the system for a performance level of 1.5, at frequency points between 0.1 and 100 rad/s.

opts = robOptions('VaryFrequency','on');
[perfmarg,wcu,info] = robgain(S,1.5,{0.1,100},opts);
info

%
% robgain returns the vector of frequencies in the info output, in the Frequencies field. info.Bounds contains the upper and lower bounds on the performance margin at each frequency. Use these values to plot the frequency dependence of the performance margin.

semilogx(info.Frequency,info.Bounds)
title('Performance Margin vs. Frequency')
ylabel('Margin')
xlabel('Frequency')
legend('Lower bound','Upper bound')

%
% When you use the 'VaryFrequency' option, robgain chooses frequency points automatically. The frequencies it selects are guaranteed to include the frequency at which the margin is smallest (within the specified range). Display the returned frequency values to confirm that they include the critical frequency.

info.Frequency
perfmarg.CriticalFrequency

%
% Alternatively, instead of using 'VaryFrequency', you can specify particular frequencies at which to compute the robust performance margins. info.Bounds contains the margins at all specified frequencies. However, these results are not guaranteed to include the weakest margin, which might fall between specified frequency points.

w = logspace(-1,2,20); 
[perfmarg,wcu,info] = robgain(S,1.5,w);
semilogx(w,info.Bounds)
title('Performance Margin vs. Frequency')
ylabel('Margin')
xlabel('Frequency')
legend('Lower bound','Upper bound')

% Copyright 2012 The MathWorks, Inc.