function x=NelderMead(f,x0,tol,maxiter,r,c,g,s)
% NELDERMEAD direct minimization algorithm by Nelder Mead
%   x=NelderMead(f,x0,tol,maxiter,r,c,g,s) tries to find a minimum of
%   f, starting at x0. The remaining parameters r, c, g, and s are
%   optional, and correspond to the parameters rho, chi, gamma, and
%   sigma; defaults are chosen, if they are not given.

if nargin<8, s=0.5; end;
if nargin<7, g=0.5; end;
if nargin<6, c=2; end;
if nargin<5, r=1; end;
if nargin<4, maxiter=100; end;
if nargin<3, tol=1e-6; end;

x=x0; k=0; fk=feval(f,x);
while k<maxiter
  [fk,id]=sort(fk); x=x(id,:);
  xb=mean(x(1:end-1,:)); xr=xb+r*(xb-x(end,:));
  fr=feval(f,xr);
  if fr>=fk(1) & fr<fk(end-1)                   % reflection step
    x(end,:)=xr; fk(end)=fr;
  elseif fr<fk(1)
    xe=xb+c*(xr-xb); fe=feval(f,xe);
    if fe<fr
      x(end,:)=xe; fk(end)=fe;
    else
      x(end,:)=xr; fk(end)=fr;
    end;
  else                                          % contraction step
    xi=xb-g*(xr-xb); fi=feval(f,xi);
    xo=xb+g*(xr-xb); fo=feval(f,xo);
    if fr<fk(end) & fo<fr
      x(end,:)=xo; fk(end)=fo;
    elseif fr>=fk(end) & fi<fk(end)
      x(end,:)=xi; fk(end)=fi;
    else                                       % shrinking step
      for j=2:size(x,1)
        x(j,:)=x(1,:)+s*(x(j,:)-x(1,:)); fk(j)=feval(f,x(j,:));
      end;
    end;
  end;
  k=k+1;
end;

