%%
J = @(x) x.*exp(-x.^2) + (x.^2)/20;
x = -10:.1:10;
y = J(x);
plot(x,y,'linewidth',2)
set(gca,'xtick',[-10:1:10])
xlabel('X'); ylabel('Y');
grid on

%%
[p,fval,eflag,output] = fminsearch(J,-6.0)

%%
[p,fval,eflag,output] = fminsearch(J,1.0)

%%
[p,fval,eflag,output] = fminunc(J,-6.0)

%%
[p,fval,eflag,output] = fminunc(J,1.0)

%% repeat the optimizer for N different initial guesses
N = 1000;
y_lowest = realmax;
p_best = 0;
opt = optimoptions('fminunc');
opt.Display = 'none';
for i=1:N
    % choose random (uniform dist) between 
    % -10 and +10
   p0 = rand*20 - 10;
   [p,fval] = fminunc(J, p0, opt);
   if fval < y_lowest
       y_lowest = fval;
       p_best = p;
   end
end

%% 2D optimization

x = linspace(-3,3,51);
y = linspace(-3,3,51);
XY = combvec(x,y);
J = mycostfun2d(XY');
[Y,X] = meshgrid(x,y);
Z = reshape(J,length(x),length(y));
figure
meshc(X,Y,Z)
shading flat
xlabel('X'); ylabel('Y'); zlabel('J')

%% optimize!
[p,fval,exitflag,output] = fminunc('mycostfun2d', [2,3])








