## Fletcher-Reeves Multidimensional optimisation
## Author: M. Turhan ÇOBAN
## Created: 2021-11-03
function retval = Fletcher_Reeves_MD_opt(f,x)
    ti=1.0;
    nmax=20;
    gamma=1.0;
    tolerance=1.0e-4;
    n=length(x);
    alpha=0.0;
    beta=0.0;
    nn=15;
    i=1;
    j=1;
    k=1;
    total=1.0;
    i=0;
    g=zeros(n,1);
    ge=zeros(n,1);
    d=zeros(n,1);
    alpha_d=0.0;
    Q=zeros(n,1);
    while  j < nmax && gamma > tolerance
        g=dfn(f,x)';
        gamma=norm(g)
        if k<2
          for i=1:n
            d(i)=-g(i);
            ge=g;
          endfor
        else
          x1=g'*g;
          x2=ge'*ge;
          x3=x1/x2;
          beta=x3;
          for i=1:n
            Q(i)=beta*d(i);
          endfor
        endif
        for i=1:n
            d(i)=-g(i)+Q(i);
        endfor       
        x1=dfn(f,x);
        fx1=@(alpha)f1dim(f,alpha,x,x1);
        alpha=newton_opt(fx1,alpha);
        for i=1:n
          xx0=x(i);
          xx1=alpha*d(i);
          xx3=xx0-xx1;
          x(i)=xx3;
        endfor
        ge=g;
        j=j+1;
        k=k+1;
        if(k>=nn) k=1;endif
        x
     endwhile # kk
  retval=x;
endfunction

function retval = norm(v)
  total=0;
  n=length(v);
  for i=1:n
    total+=v(i)*v(i);
  endfor  
  retval=sqrt(total);
endfunction  