% Nelder-Mead simplex method

clear

n=2;

f=@(x) x(:,1).^2-4*x(:,1)+x(:,2).^2-x(:,2)-x(:,1).*x(:,2);

x=[0 0;
   1.2 0;
   0 0.8];

%figure;fill(x(:,1),x(:,2),'r','facealpha',.05); % alt graphics in MATLAB
figure;patch(x(:,1),x(:,2),[1 1 1],'facecolor','r','edgecolor','k')
hold on;

Niterations=12;
for iteration=1:Niterations
    
    sortedset=sortrowsAlt([f(x) x],1);
    x=sortedset(:,2:3);
    
    c=mean(x(1:n,:));
    xref=2*c-x(n+1,:);
    
    if f(x(1,:))<=f(xref) && f(xref)<=f(x(n,:))
        x(n+1,:)=xref;
        disp('reflection step')
    elseif f(xref)<f(x(1,:)) % expansion step
        xexp=2*xref-c;
        if f(xexp)<f(xref)
            x(n+1,:)=xexp;
        else
            x(n+1,:)=xref;
        end
        disp('expansion step')
    else % contraction step f(xref)>f(x(n,:))
        if f(xref)>=f(x(n+1,:))
            xcon=0.5*(x(n+1,:)+c);
        else
            xcon=0.5*(xref+c);
        end
        if f(xcon)<f(x(n,:))
            x(n+1,:)=xcon;
        else
            x=(repmat(x(1,:),n+1,1)+x)/2;
        end
        disp('contraction step')
    end
    
    [f(x) x]
    patch(x(:,1),x(:,2),[1 1 1],'facecolor',[1 iteration/Niterations 0],'edgecolor','k')
    %fill(x(:,1),x(:,2),'r','facealpha',iteration/10); % alt graphics in MATLAB
end

fminsearch(f,[0 0])