%System with good phase and gain margins but low stability margin
%   kja 070510

aminit;

%
% Nyquist plot
%

w=0.1:0.005:10;
Ln=0.38*conv([0 0 1],[1 0.1 0.55]);
Ld=conv([1 1 0],[1 0.06 0.5]);
L=tf(0.38,[1 1 0]);
N=tf([1 0.1 0.55],[1 0.06 0.5]);
L1=L*N;

%Nyquist plot
figure(1); clf; subplot(221);
ampolezero(tf([1], [1]), [-1.5 1.5 -1.5 1.5]);
axis square;

[x,y]=nyquist(L1, w);x=x(:);y=y(:);
pl=plot(x, y, 'b-', 'Linewidth', AM_bode_linewidth);

fi=0.01:0.01:2*pi;
hold on; plot(cos(fi), sin(fi), 'k--', 'Linewidth', AM_ref_linewidth);

[xxx,ii]=min(abs(y));y(ii),x(ii),Am=1/x(ii)
[xxx,ii]=min(abs(x.^2+y.^2-1));phim=180/pi*atan(y(ii)/x(ii))
[xxx,ii]=min(abs((x+1).^2+y.^2));Ms=1/sqrt(xxx)

amprint('niklas-nyq.eps');

%
% Bode Plot
%

figure(2); clf; axes('position', [0.1 0.55 0.2 0.3]);
[mh, ph] = ambode(L1, w); 

axes(mh); hold on;
plot([0.1 10], [1 1], 'k-', 'LineWidth', AM_ref_linewidth);
axis([0.1 2 0.1 10]);
ylabel('gain');

axes(ph); hold on;
plot([0.1 10], [-180 -180], 'k-', 'LineWidth', AM_ref_linewidth);
axis([0.1 2 -190 -90]);
ylabel('phase');
xlabel('w');

%Closed loop poles
clpoles=roots(Ln+Ld);

amprint('niklas-bode.eps');

%
%Step response
figure(3); clf;
t=0:0.01:150;
T=L1/(1+L1);
T1=tf(Ln,Ld+Ln);
[y,t]=step(T,t);
[y1,t]=step(T1,t);

axes('position', [0.1 0.55 0.3 0.3]);
pl=plot(t,y1,'b-');
set(pl,'Linewidth', AM_data_linewidth);
axis([0 150 0 1.5]);
line([0 150],[1 1]);
xlabel('x');ylabel('y');

daspect(daspect * diag([1 1 1]));

amprint('niklas-step.eps');
