%% Gain and Phase Variations in a MIMO Feedback Loop
% The umargin block represents a SISO gain and phase uncertainty. To model gain and phase variations in a MIMO feedback loop, create a umargin block for each location in the loop at which you want to introduce gain and phase variation. For instance, consider the two-input, two-output feedback loop of the example MIMO Stability Margins for Spinning Satellite.
%
% Suppose that you want to study the system's behavior with gain and phase variations at the plant inputs and outputs. You can model those variations by creating separate umargin blocks for each channel, and building them into the closed-loop model.
%
%
% Create the plant and controller models from MIMO Stability Margins for Spinning Satellite. The plant is a two-input, two-output state-space model, and the feed-forward filter Kf is a two-input, two-output static gain.

% Plant
a = 10;
A = [0 a;-a 0];
B = eye(2);
C = [1 a;-a 1];
D = 0;
P = ss(A,B,C,D);

% Prefilter
Kf = [1 -a;a 1]/(1+a^2);

%
% Next, create the umargin blocks to represent the gain and phase uncertainty in each channel. Suppose that you want to model a gain uncertainty of about 5% in either direction at all four locations. Create a umargin block to model this uncertainty.

GM = 1.05;
u1 = umargin('u1',GM)

% umargin converts the specifed gain variation of ±5% to a disk-based uncertainty model, which also allows phase changes of about ±3°. Use plot to visualize the disk and the modeled range of gain and phase variation at each input and output.

plot(u1)

%
% To get the best estimates of the impact of gain and phase uncertainty on system performance, you want the gain and phase to vary independently at each of the four locations. Therefore, create additional umargin blocks for each plant input and output, with the same gain specification.

u2 = umargin('u2',GM);
y1 = umargin('y1',GM);
y2 = umargin('y2',GM);

%
% Build the closed-loop model, inserting u1 and u2 at the plant inputs, and y1 and y2 at the plant outputs. To do this, use blkdiag to combine u1 and u2 into a two-input, two-output system of the form [u1,0;0,u2]. Create a similar combination of y1 and y2.Then connect these with the plant, and use the feedback command to close the two-channel feedback loop.

Fu = blkdiag(u1,u2);
Fy = blkdiag(y1,y2);
L = Fy*P*Fu;    
Tunc = feedback(L,eye(2))*Kf

%
% Examine the effect of these variations on the system response.

rng(1)  % for reproducibility
figure
step(Tunc,Tunc.NominalValue,10)

% These small uncertainties have a considerable impact on system performance, sometimes even changing the sign of the response. Robustness analysis with robstab shows that only a slightly larger variation drives the closed-loop system unstable.

stabmarg = robstab(Tunc)

%
% Copyright 2019 The MathWorks, Inc.