%sliding_opt.m

clear

A=[5 1;-5 1;-1 -2];
b=[0 10 10]';
Q=[4 1;1 2];
c=[-12 -10]';

% plot the linear constraints

m=length(A);   
vertex=zeros(m,2);
X=linspace(-8,8,50);
Y=linspace(-8,8,50);

for i = 1:m;
   idx=[1:i-1 i+1:m];
   vertex(i,:)=b(idx)'*inv(A(idx,:))'; 
   y=-(A(i,1)*X-b(i))/A(i,2);
   plot(X,y,'k');hold on;
end;

patch(vertex(:,1),vertex(:,2),[.8 .8 .8])
axis([-7 7 -7 7]);
axis square
hold on
set(gca,'Fontsize',12)
xlabel('{\it x}_1','Fontsize',12)
ylabel('{\it x}_2','Fontsize',12)
title('Interactive phase portrait of Example 6.5','Fontsize',12)
% plot the objective function
[xm,ym]=meshgrid(X,Y);
z=.5*(Q(1,1)*xm.^2+2*Q(2,1)*xm.*ym+Q(2,2)*ym.^2)+c(1)*xm+c(2)*ym;
%z=4*xm.^2+ym.^2;
contour(xm,ym,z,[-30 -25 -17 -5 10 30 60 100 150 200]);

button = 1;
while button ~= 3;
   [xi,yi,button]=ginput(1);
   [t,sol]=ode23s('opt_func',[0 50],[xi yi]);
   plot(sol(:,1),sol(:,2),'r','linewidth',2);
   lastidx=length(sol(:,1));
   plot(sol(lastidx,1),sol(lastidx,2),'r.','markersize',20)
   
end;
hold off;