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:
- x is the vector of x co-ordinates of the points to cover
- y is the vector of y co-ordinates of the points to cover
- 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:
- Defines the points to be covered. (x and y vectors)
- Uses the “polyfit” function to find the coefficient matrices for line and quadratic curve.
- To validate the results, we define another vector “h”. Interval is only 0.1
- Plot the line and the quadratic curve.
Here is the resulting plot:
Observe the following facts from the above figure.
- Points are shown blue.
- The red line is best fitting line covering all the points. Its equation is:
- The green curve is the best fitting quadratic curve with equation:
You can download the octave script Polyfit_octave here.