%  Figure 6.59      Feedback Control of Dynamic Systems, 8e
%                   Franklin, Powell, Emami
%   

clear all
close all
clf
 
w=logspace(-1,2,100);

num = 10;

den = conv([1 0],[1/2.5 1]);
den = conv(den,[1/6 1]);

[mag,phas] = bode(num,den,w);
[OLgm,OLpm,OLwcg,OLwcp] = margin(mag,phas,w);
data0 = [OLgm,OLpm,OLwcg,OLwcp]


%Lead compensator
numl = 10*[1 2];
denl = [1 20];

num1 = conv(num,numl);
den1 = conv(den,denl);

[magcl,phascl] = bode(num1,den1,w);
[D1gm,D1pm,D1wcg,D1wcp] = margin(magcl,phascl,w);
data1 = [D1gm,D1pm,D1wcg,D1wcp]


numll = 10*conv(numl,[1 4]);
denll = conv(denl,[1 40]);

num2 = conv(num,numll);
den2 = conv(den,denll);

[magcll,phascll] = bode(num2,den2,w);
[D2gm,D2pm,D2wcg,D2wcp] = margin(magcll,phascll,w);
data2 = [D2gm,D2pm,D2wcg,D2wcp]

[data0; data1; data2]

figure(1)
subplot(2,1,1)

loglog(w,mag,'-',w,ones(100,1),'-',w,ones(100,1),'-',w,ones(100,1),'-','LineWidth',2);

text( 5*0.1, 5, "K = 1")

axis([.1 100 .1 100])
grid on;
ylabel('Magnitude');
title('Bode plot for Example 6.17.   (a) magnitude');

subplot(2,1,2)
semilogx(w,phas,'-',w,-180*ones(100,1),w,-180*ones(100,1),w,-180*ones(100,1), 'LineWidth',2);

axis([.1 100 -250 -50])
grid on;
xlabel('\omega (rad/sec)');
ylabel('phase (deg)');
title('(b) phase.');



figure(2)

subplot(2,1,1)

loglog(w,ones(100,1),'-',w,magcl,'--',w,ones(100,1),'-',w,ones(100,1),'-','LineWidth',2);

text( 5*0.1, 1.5, "D_c = [1 2]/0.1*[1 20]")

axis([.1 100 .1 100])
grid on;
ylabel('Magnitude');
title('Bode plot for Example 6.17.   (a) magnitude');

subplot(2,1,2)
semilogx(w,-180*ones(100,1),'-',w,phascl,'--',w,-180*ones(100,1),w,-180*ones(100,1),'LineWidth',2);

axis([.1 100 -250 -50])
grid on;
xlabel('\omega (rad/sec)');
ylabel('phase (deg)');
title('(b) phase.');



figure(3)


subplot(2,1,1)

loglog(w,ones(100,1),'-',w,ones(100,1),'-',w,magcll,'-.',w,ones(100,1),'-','LineWidth',2);

text( 5*1, 5, "D_c = [1 2]*[1 4] / (0.1)^2*[1 20]*[1 40]")

axis([.1 100 .1 100])
grid on;
ylabel('Magnitude');
title('Bode plot for Example 6.17.   (a) magnitude');

subplot(2,1,2)
semilogx(w,-180*ones(100,1),w,-180*ones(100,1), w,phascll,'-.',w,-180*ones(100,1),'LineWidth',2);

axis([.1 100 -250 -50])
grid on;
xlabel('\omega (rad/sec)');
ylabel('phase (deg)');
title('(b) phase.');



figure(4)


subplot(2,1,1)

loglog(w,mag,'-',w,magcl,'--',w,magcll,'-.',w,ones(100,1),'-','LineWidth',2);

text( 5*0.1, 5, "K = 1")
text( 5*0.1, 1.5, "D_c = [1 2]/0.1*[1 20]")
text( 5*1, 5, "D_c = [1 2]*[1 4] / (0.1)^2*[1 20]*[1 40]")

axis([.1 100 .1 100])
grid on;
ylabel('Magnitude');
title('Bode plot for Example 6.17.   (a) magnitude');

subplot(2,1,2)
semilogx(w,phas,'-',w,phascl,'--',w,phascll,'-.',w,-180*ones(100,1),'-','LineWidth',2);

axis([.1 100 -250 -50])
grid on;
xlabel('\omega (rad/sec)');
ylabel('phase (deg)');
title('(b) phase.');
