clear all
close all
format short

%% Only used for visualization
fXY = @(x,y) 5*x.^2+x.*y+0.5*y.^2-x; %defined with (x_1,x_2) = (x,y) so we can use it in the contour plot.
[X,Y] = meshgrid(linspace(-0.01,0.2),linspace(-0.2,0.01));
Z = fXY(X,Y);
contour(X,Y,Z,[-0.0556+eps*2.^(0:60)]);
hold on
    
%% Algorithm
H = [10 1;1 1];
f = @(x) 0.5*x'*(H*x)-x(1);
gradF = @(x)H*x -[1;0];
x{1} = [0.2;0.1];
plot([x{1}(1)], [x{1}(2)], 'ro','linewidth',2)
pause(2)

iter = 6;
xVec = x{1};
fVec = f(x{1});

for k =1:6
s{k} = -gradF(x{k});
alpha{k} = -gradF(x{k})'*s{k}/(s{k}'*H*s{k}); %sedan f ar kvadratisk galler denna steglangdsformeln
x{k+1} = x{k} +alpha{k}*s{k};

%Visualization
plot([x{k}(1) x{k+1}(1)], [x{k}(2) x{k+1}(2)], 'r-o','linewidth',2)
pause(2.5)

xVec = [xVec x{k+1}];
fVec = [fVec f(x{k+1})];

end

xVec  
fVec 

xRef = fminsearch(f,x{1}) %matlabsolver