## Polynomial least square
## Author: M. Turhan COBAN
## Created: 2021-08-21

function retval = poly_least(x,y,n)
    #Polynomial least square
    ## this function calculates leat square polynomial coefficient a
    ## a=[a0 a1 a2 a3..]
    ## where f=a0+a1*x+a2*x^2+a3*x^3+.
    m=length(x);
    np1=n+1;   
    A =zeros(np1,np1); 
    B =zeros(np1); 
    X =zeros(np1); 
    x1=0.0;
    for i=1:np1 
        for j=1:np1
            if i==1 && j==1 
                A(i,j)=m;
            else  
                for k=1:m
                    x1=x(k);
                    pp=x1^(i+j-2);
                    A(i,j)= A(i,j)+pp;
                end # for k=1:m
            end # for if
         end # j=1:   
        for k=1:m
            if i==1 
                B(i)=  B(i)+y(k);
            else
                x1=x(k);
                B(i)= B(i)+x1^(i-1)*y(k);
            end # if i==0
        end # for k=1:m
    end # for i=1:np1
    xx=A\B;##gauss1(A,B);
    retval=xx(:,1)';
endfunction
