%% Reduce Synthesized Controller While Preserving Robust Performance
% When you use musyn to synthesize an unstructured robust controller, the resulting controller often is of higher order than is necessary to achieve the desired robust performance. One way to mitigate this problem is to perform model reduction, using musynperf to test the robust performance of the reduced-order controller.
%
% Create an uncertain model of the control system described in the example "Robust Tuning of Fixed-Structure Controller" on the musyn reference page.

G = tf(1,[1 -1]);
Wu = 0.25*tf([1/2 1],[1/32 1]); 
InputUnc = ultidyn('InputUnc',[1 1]);
Gpert = G*(1+InputUnc*Wu);
Gpert.InputName = 'u';
Gpert.OutputName = 'y1';

Wp = makeweight(100,[1 0.5],0.25);
Wp.InputName = 'y';
Wp.OutputName = 'e';

SumD = sumblk('y = y1 + d');
inputs = {'d','u'};
outputs = {'e','y'};
P = connect(Gpert,Wp,SumD,inputs,outputs); 

[K,CLperf] = musyn(P,1,1); 
N = order(K)

%
% musyn returns an 11th-order controller and the robust H_{\infty } performance CLperf of the closed-loop system using that controller. The best achieved robust performance of about 0.65 is good, but the controller order is high. Compute reduced-order controllers for orders ranging from 1 to full order.

Kred = reduce(K,1:N);

%
% Find the lowest-order controller Klow with performance no worse than 1.05*CLperf, or 5% degradation compared to the full-order controller.

for k=1:N
   Klow = Kred(:,:,k);
   CL = lft(P,Klow);
   [gamma,~] = musynperf(CL);
   if gamma.UpperBound < 1.05*CLperf
      break
   end
end 
order(Klow)

%
% To validate the reduced-order controller, examine the robust H_{\infty } performance of the system using the simplified controller with that of the system using the full-order controller.

CLPlow = lft(P,Klow);
[gammalow,~] = musynperf(CLPlow);
gammalow.UpperBound

%
% The fourth-order controller achieves very similar robust H_{\infty } performance to the 11th-order controller returned by musyn.
%
% Copyright 2019 The MathWorks, Inc.