%     UnstablePLS.m
%
%  shows that switching between two stable linear systems may
%  result in an unstable behaviour
%
% J. Lunze
% 16.6.2008
% für ESAufl4: 3.3.2025
clear 
close all
%
A1=[-1 10; -100 -1];
A2=[-1 100; -10 -1];
x0=[1; 0];
Tmax=1;
dt=0.0001;                   % simulation time step
kmax=Tmax/dt;
T=[0:dt:Tmax];
%
%    Behaviour of the linear systems
%
figure(1)
System1=ss(A1, [], eye(2), []);
[Y, T, X]=initial(System1, x0, T);
%
subplot(1,2,1)
plot(X(:,1), X(:,2), 'b');
hold on
plot([-3 3],[0 0],'k:', [0 0],[-3 3],'k:');
plot(x0(1), x0(2), 'bo');
hold off
latexxlabel('$$x_1$$');
latexylabel('$$x_2$$');
rotateY;
axis([-3 3 -3 3]),
axis('square');
yticks([-2 0 2]);
xticks([-2 0 2]);
%
System2=ss(A2, [], eye(2), []);
x0=[0; 1];
[Y, T, X]=initial(System2, x0, T);
subplot(1,2,2)
plot(X(:,1), X(:,2), 'b');
hold on
plot([-3 3],[0 0],'k:', [0 0],[-3 3],'k:');
plot(x0(1), x0(2), 'bo');
hold off
latexxlabel('$$x_1$$');
latexylabel('$$x_2$$');
rotateY;
axis([-3 3 -3 3]),
axis('square');
yticks([-2 0 2]);
xticks([-2 0 2]);

%
%
%  Reset rule
%  if x_1*x_2 < 0 then A1 else A2
figure(2)
x0=[1; 0];
eA1dt=expm(A1*dt);
eA2dt=expm(A2*dt);
x(1,:)=x0;
if x0(1)*x0(2) < 0
   Ad=eA1dt;
else
   Ad=eA2dt;
end
for k1=2:kmax
    x(k1,:)=(Ad*x(k1-1,:)')';
    if x(k1,1)*x(k1,2)<0
       Ad=eA1dt;
    else
       Ad=eA2dt;
    end
end
plot(x(:,1), x(:,2), 'b')
axis(100000*[-12 12 -20 5]);
axis('square');
hold on
plot([-4000000 4000000],[0 0],'k:', [0 0], [-4000000 4000000], 'k:');
latexxlabel('$$x_1$$');
latexylabel('$$x_2$$');
rotateY;
text(0.6*1000000, -10*100000, '\downarrow');
hold off
yticks([-2000000 -1000000 0 1000000 2000000]);
xticks([-1000000 0 1000000]);


%
%%
%  Inverted reset rule
%  if x_1*x_2 > 0 then A1 else A2
figure(3)
x0=[1; 0];
x=[];
x(1,:)=x0';
if x0(1)*x0(2) < 0
   Ad=eA2dt;       % exchanged
else
   Ad=eA1dt;
end
for k1=2:kmax
    x(k1,:)=(Ad*x(k1-1,:)')';
    if x(k1,1)*x(k1,2)<0
       Ad=eA2dt;       % exchanged
    else
       Ad=eA1dt;
    end
end
plot(x(:,1), x(:,2), 'b')
axis([-0.2 1.1 -0.5 0.8]);
axis('square');
hold on
plot(x(1,1), x(1,2), 'bo');
plot([-4 4],[0 0],'k:', [0 0], [-4 4], 'k:');
latexxlabel('$$x_1$$');
latexylabel('$$x_2$$');
rotateY;
text(0.1, -0.4, '\leftarrow');
yticks([-0.5 0 0.5 1]);
xticks([-0.5 0 0.5 1]);
hold off



%%
%
epsfigc('UnstabPLS');
