%% minmax2d.m 
% Shortend and modified file from the 
% Optimization Toolbox™ tutorial, HA 21.2.2018
% 
%% Unconstrained Optimization Example
% Consider the problem of finding a minimum of the function:
% 
% $$x\exp(-(x^2+y^2))+(x^2+y^2)/20.$$
% 
% Plot the function to get an idea of where it is minimized

f = @(x,y) x.*exp(-x.^2-y.^2)+(x.^2+y.^2)/20;
fsurf(f,[-2,2],'ShowContours','on')
%% Just use min for matrix elements (no fancy methods):
x=linspace(-2,2,200); y=x;
[X,Y]=meshgrid(x,y);
z=f(X,Y);
[val,ind]=min(z(:))
[X(ind),Y(ind)]
hold on
plot3(X(ind),Y(ind),val,'*')

%% Increase accuracy by fminsearch (does it?)
% fminsearch wants fun to have one vector input
% (instead of x,y).
fun = @(x) f(x(1),x(2));
[m,n]=size(X)
X1=X(:);Y1=Y(:);
z=zeros(3,m*n);
for k=1:m*n  
       [x,val]=(fminsearch(fun,[X1(k) Y1(k)]));
       z(:,k)=[x';val];
end    

%% Change for to parfor
% Measure tic-toc-timing difference especially
% on Triton. (parfor uses all available (24) workers.)
