% T84e.m

format compact
clc
clear

% syms s;
% Ds = expand ((s+1)*(s+2)*(s+3))     % expand pole terms to poly expression
% Ds = s^3+6*s^2+11*s+6
% D = poly ([-1 -2 -3])               % convert poles to polynomial
N = [1];
D = [1 6 11 6];
% N = [1 3];
% D = [1 -2 0];
G = tf (N, D)
rlocus (G)

% Select system gain
disp ('stability condition: K < 60')
% disp ('stability condition: K > 2')
K = input ('Enter K: ');

% Bode plot
figure     % for new window
bode (K*G)

% checking specific values on Bode Plot
w = input ('Enter w: ')
Gjw = evalfr (K*G, j*w);
Gmag = abs(Gjw),  Garg = angle(Gjw) * 180/pi
dB = 20 * log10(Gmag)

% closed loop poles
T = feedback (K*G, 1)
% alternative:
% T = K*G / (1 + K*G)
% T = minreal (T)
closed_loop_poles = pole(T)

% Nyquist plot
figure
nyquist (K*G)
% figure
% nyquist (K*G, {1, 1000})   % to look at smaller freq. range (close to -1)

% Compute system margins
% figure, margin (K*G)     % to display Bode diagram with margin display
% [gm,pm,wg,wp] = margin (K*G)
% gm_dB = 20 * log10(gm)

% pause for the user and remove figures
display ('Hit Enter to continue');
pause
close all
