%% Global minimization
%
%% Function to minimize
f = @(x) x.*sin(x) + x.*cos(2.*x)
% Find global minimum (and local minima) on [0,12].
% Split the interval into pieces and use fminbnd on each piece.
% Bounds:
%lb = 0; ub = 12;
%
%% Split into several parts:
lb=[0 1 3 6 8 10];  % Lower bounds
ub=[lb(2:end) 12];  % Upper bounds
x0=0.5*(lb+ub);     % Starting points for solver that requires them.

%% fminbnd, only bounds are needed, no starting points.
x=zeros(6,1);
tic
for i=1:6 
    x(i) = fminbnd(f,lb(i),ub(i));             
    subplot(2,3,i)
    ezplot(f,[lb(i) ub(i)]);
    hold on
    % plot(x0(i),f(x0(i)),'k+') % For solver that needs init. points.
    plot(x(i),f(x(i)),'ro') % Plot "labwise" minimum point (red circle)
    hold off
    title(['Bounds: [',num2str(lb(i)),',',num2str(ub(i)),']'])
    if i == 1 || i == 4
        ylabel('x sin(x) + x cos(2 x)')
    end
end
%% Global minimum, and local minima
[ymin,imin]=min(f(x))
xmin=x(imin)
figure
xx=linspace(lb(1),ub(end));
plot(xx,f(xx),x,f(x),'ro') 
%% Task: 
% Enlarge interval to [-2,14]
% (a) Change for to parfor, run on pc and Triton, do tic - toc- timing.
% (b) Change to spmd, on Triton you can take more labs than 6.
% (c) Find max-points as well.
%% Optim. toolbox: fmincon (Just for studying more involved tools.)
%
for i=1:6
 
    x(i) = fmincon(f,x0(i),[],[],[],[],lb(i),ub(i),[],...
                   optimset('Algorithm','SQP','Disp','none'));
    subplot(2,3,i)
    ezplot(f,[lb(i) ub(i)]);
    hold on
    plot(x0(i),f(x0(i)),'k+')
    plot(x(i),f(x(i)),'ro')
    hold off
    title(['Starting at ',num2str(x0(i))])
    if i == 1 || i == 4
        ylabel('x sin(x) + x cos(2 x)')
    end
end
