% adaptQuadratic - iteratively find minimum of a quadratic function

%% Initialization
N = 300;
mu = 0.6;
x = zeros(1,N);
z = zeros(1,N);
x(1) = 3;
z(1) = x(1)^2-4*x(1)+4;

xx = 0:0.005:4;
JJ = xx.^2 - 4*xx + 4;

%% Iteration
for nn=1:N-1
    x(nn+1) = x(nn)*(1-2*mu) + 4*mu;
    z(nn+1) = x(nn+1)^2-4*x(nn+1)+4;
    
    figure(1);
    plot(xx,JJ,'b', x(nn+1), z(nn+1), 'ro')
    grid on
    xlabel('x')
    ylabel('J(x)')
    title(sprintf('Iteration %d', nn+1))
    
    pause(1/20);
end

%% Plots
figure(2)
plot(0:N-1, x, 'b', [0,N-1], 2*ones(1,2), 'r--');
axis([0, N, 0, 4])
grid on
xlabel('Iteration (n)')
ylabel('x[n]')

figure(3)
plot(0:N-1, z, 'b', [0,N-1], 0*ones(1,2), 'r--');
axis([0, N, -1, 1])
grid on
xlabel('Iteration (n)')
ylabel('J(x[n])')
