%  Example 5.4.  Stability margin computation.
clear
%  Define the plant transfer function.
nup=1;
dep=[1 -2 1];
%  Define the controller transfer function.
nuk=[1500 -100];
dek=[1 30 400];
%  Generate the loop transfer function.
nu=conv(nup,nuk);
de=conv(dep,dek);
%  Compute bode plots to used in computing the stability margins.
w=logspace(-2,2,100);
[mag,pha]=bode(nu,de,w);
%  Note: Different frequency bands are used for computing the gain
%  margins and the phase margins due to the complicated loop transfer function.
%  Compute the gain margin.
Gm=margin(mag(1:5),pha(1:5),w(1:5));
%  Compute the downside gain margin.
Gmd=margin(mag(6:60),pha(6:60),w(6:60));
%  Compute the phase margin.
[Gmw,Pm,Wg,Wp]=margin(mag(61:100),pha(61:100),w(61:100));
%  Display the gain margin, downside gain margin, and phase margin.
[Gm,Gmd,Pm]
