% simple.m - Bode and Nyquist plots for a simple third order transfer function
% RMM, 14 Jul 07

aminit;

sys = tf([3], [1 3 3 1]);
[gm, pm, wcg, wcp] = margin(sys);

figure(1); clf; xsubplot(221);
amaxis([-1.5 4.5 -3 3]); daspect(daspect); hold on;
amnyquist(sys); 

% Mark the -1 point
amtext(-1.45, -0.3, '-1');

% Add circle for phase margin
theta = -pi+0.05:0.01:pi-0.05
plot(cos(theta), sin(theta), 'k--', 'linewidth', AM_ref_linewidth);

% Mark the locations for the gain and phase margins
H = freqresp(sys, wcg);
plot(real(H), imag(H), 'ro', 'markersize', AM_bode_markersize);

H = freqresp(sys, wcp);
plot(real(H), imag(H), 'ro', 'markersize', AM_bode_markersize);

amprint('simple-nyquist.eps');

figure(2); clf; subplot(221);
[mh, ph] = ambode(sys);

% Plot the margins
axes(mh); hold on;
plot(wcg, 1/gm, 'ro', 'MarkerSize', AM_bode_markersize);
plot([wcg wcg], [1 1/gm], 'r-', 'LineWidth', AM_ref_linewidth);
plot([0.1 10], [1 1], 'Color', 'k', 'LineWidth', AM_ref_linewidth);

axes(ph); hold on;
plot(wcp, -180+pm, 'ro', 'MarkerSize', AM_bode_markersize);
plot([wcp wcp], [-180 -180+pm], 'r-', 'LineWidth', AM_ref_linewidth);
plot([0.1 10], [-180 -180], 'Color', 'k', 'LineWidth', AM_ref_linewidth);

amprint('simple-bode.eps');

% To compute the stability margin, we compute the closest distance to -1
W = logspace(-1, 1);
H = freqresp(sys, W);
sm = min(abs(H + 1));
