function ShowSPDopt()
close all
clc
% A 2x2 symmetric p[ositive definite system...
A = [3 2; 2 2];
xStar = rand(2,1);
b = A*xStar;
% Display the contours of phi(x) = x'Ax/2 - x'b
Display1(A,b,3)
% Click in a starting value
title('Click in a starting value...','fontsize',16)
hold on
x = zeros(2,1);
[x(1),x(2)] = ginput(1);
plot(x(1),x(2),'.r','Markersize',25)
title('Ready to start the method of steepest descent...','fontsize',16)
xlabel(sprintf('|| x - xStar || = %10.3e',norm(x-xStar)),'fontsize',16)
hold off
shg
pause(3)
for step=1:6
title('The Steepest Descent Step.','fontsize',16)
g = A*x - b;
mu = g'*g/(g'*A*g);
xNew = x - mu*g;
hold on
plot(xNew(1),xNew(2),'.r','Markersize',25)
plot([x(1) xNew(1)],[x(2) xNew(2)],'r','linewidth',2)
hold off
xlabel(' ')
pause(3)
d = 1.5*norm(xNew-xStar);
Display1(A,b,d)
title('The Current x','fontsize',16)
x = xNew;
hold on
plot(x(1),x(2),'.r','Markersize',25)
xlabel(sprintf('|| x - xStar || = %10.3e',norm(x-xStar)),'fontsize',16)
hold off
pause(3)
end
hold off

function Display1(A,b,d)
% Display contours of the function phi(x) = x'Ax/2 - x'b
close
xStar = A\b;
N = 200;
x1Vals = linspace(xStar(1)-d,xStar(1)+d,N);
x2Vals = linspace(xStar(2)-d,xStar(2)+d,N);
phiVals = zeros(N,N);
for i=1:N
for j=1:N
x = [x1Vals(j);x2Vals(i)];
phiVals(i,j) = (x'*A*x)/2 - x'*b;
end
end
phiMin = min(min(phiVals));
phiMax = max(max(phiVals));
del = phiMax-phiMin;
v = phiMin + [0 del/1024 del/512 del/256 del/128 del/64 del/16 del/8 del/4 del/2 del];
contour(x1Vals,x2Vals,phiVals,v)
hold on
plot(xStar(1),xStar(2),'.g','Markersize',25)
title(sprintf('x = [ %5.2f ; %5.2f ]',xStar(1),xStar(2)),'fontsize',16)
axis([xStar(1)-d xStar(1)+d xStar(2)-d xStar(2)+d])
axis square
hold off
set(gcf,'position',[100 100 600 600])
shg