clear; close all; clc;

%% The objective function is defined in f.m

% Parameters

x0 = [0;0];
t0 = 5 ;
beta = 0.5 ;
eps = 1e-5 ;

% Exercise 11
% D = [ 1 0 -1  0 ; 
%       0 1  0 -1 ] ;  

% Exercise 12
D = [ 1 0 -1 ; 
      0 1 -1 ] ;
  
%% method

fprintf('Directional Direct-search method\n\n');
fprintf('iter \t x(1) \t\t x(2) \t\t f(x) \n\n');

iter = 0;
x = x0;
t = t0; 
v = f(x);
fprintf('%1.0f \t %1.4e \t %1.4e \t %1.8e\n',iter,x(1),x(2),v);
plot(x(1), x(2),'r.');
axis([-6 6 -6 6]);
hold on;

while t > eps   
    iter = iter + 1;
    % search a better point
    i = 1;
    while i <= size(D,2)
        newx = x+t*D(:,i);
        newv = f(newx) ;
        if newv >= v 
            i = i + 1 ;
            plot(newx(1),newx(2),'bs');
%             pause
        else
            break
        end
    end
    if newv < v
        % successful iteration
        x = newx ;
        v = newv ;
        plot(x(1), x(2),'r.');
        fprintf('%1.0f \t %1.4e \t %1.4e \t %1.8e\n',iter,x(1),x(2),v);     
    else
        % step size reduction
        t = beta*t;
    end
end
