%% Stability Margins of Closed-Loop System
% Compute the stability margins of the following closed-loop system  at an analysis point specified by an AnalysisPoint block, X.
%
% Create a model of the system by specifying and connecting a numeric LTI plant model G, a tunable controller C, and the AnalysisPoint block X.

G = tf([1 2],[1 0.2 10]);
C = pid(0.1,1.5);
X = AnalysisPoint('X');  
T = feedback(G*X*C,1);

% T is a genss model that represents the closed-loop response of the control system from r to y. The model contains the AnalysisPoint block X that identifies the potential loop-opening location.
%
% By default, getLoopTransfer returns a transfer function L at the specified analysis point such that T = feedback(L,1,+1). However, margin assumes negative feedback, so that margin(L) computes the stability margin of the negative feedback closed-loop system feedback(L,1). Therefore, to analyze the stability margins, set the sign input argument to -1 to extract a transfer function L such that T = feedback(L,1). In this example, this transfer function is L(s) = C(s)G(s).

L = getLoopTransfer(T,'X',-1);

% This command computes the open-loop transfer function from the input of G to the output of C, assuming that the loop is closed with negative feedback, so that you can use it with analysis commands like margin.
%

[Gm,Pm] = margin(L)

%
% Copyright 2012 The MathWorks, Inc.