# Polyfit We take readings while experimenting. Due to unavoidable experimental errors, points don’t follow some exact mathematical rule . To find this rule, we use “Polyfit” function from GNU Octave.

In an experiment, suppose following points are recorded:  (0,3), (2,1),(3,-1),(5,-2) Now the curve that describes the rule best, must be found out. Many times a straight line is desired (linearity is the most convenient feature). The straight line should be such that it covers all the points. The curve (or line) can be the best fit if the total of the squares of the distances of all the points from the expected line is minimum (so that the deviation errors cancel out).

The “Polyfit” function uses the least square method for finding the best fitting curve. In its simplest form the command appears like this:

p = polyfit(x,y,N)

The output of the above command is a vector “p”. It contains the co-efficients of the polynomial that describes the curve best. The input arguments are:

1. x is the vector of x co-ordinates of the points to cover
2. y is the vector of y co-ordinates of the points to cover
3. N is the degree of the polynomial. If it is 1, line fitting the points is found. If N = 2, quadratic curve is found. For N = 3 coefficient matrix of a cubic spline is calculated. The above script does the following things:

1. Defines the points to be covered. (x and y vectors)
2. Uses the “polyfit” function to find the coefficient matrices for line and quadratic curve.
3. To validate the results, we define another vector “h”. Interval is only 0.1
4. Plot the line and the quadratic curve.

Here is the resulting plot: Observe the following facts from the above figure.

1. Points are shown blue.
2. The red line is best fitting line covering all the points. Its equation is: $y = -1.0385 x+2.8462$
3. The green curve is the best fitting quadratic curve with equation: $y = 0.0833 x^2-1.455128 x+3.096154$