Search code examples
polynomial-mathscilabapproximation

How to make a polynomial approximation in Scilab?


I've a set of measures, which I want to approximate. I know I can do that with a 4th degree polynomial, but I don't know how to find it's five coefficients using Scilab.

For now, I must use the user-friendly functions of Open office calc... So, to keep using only Scilab, I'd like to know if a built-in function exists, or if we can use a simple script.


Solution

  • There is no built-in polyfit function like in Matlab, but you can make your own:

    function cf = polyfit(x,y,n)
    A = ones(length(x),n+1)
    for i=1:n
        A(:,i+1) = x(:).^i
    end
    cf = lsq(A,y(:))
    endfunction
    

    This function accepts two vectors of equal size (they can be either row or column vectors; colon operator makes sure they are column-oriented in the computation) and the degree of polynomial.

    It returns the column of coefficients, ordered from 0th to the nth degree.

    The computational method is straightforward: set up the (generally, overdetermined) linear system that requires the polynomial to pass through every point. Then solve it in the sense of least squares with lsq (in practice, it seems that cf = A\y(:) performs identically, although the algorithm is a bit different there).

    Example of usage:

    x = [-3 -1 0 1 3 5 7]
    y = [50 74 62 40 19 35 52]
    cf = polyfit(x,y,4)
    
    t = linspace(min(x),max(x))'   // now use these coefficients to plot the polynomial
    A = ones(length(t),n+1)
    for i=1:n
        A(:,i+1) = t.^i
    end
    plot(x,y,'r*')
    plot(t,A*cf)
    

    Output:

    polynomial fit