# MATLAB Polyfit Simulation Tutorial: Everything to Know

Table of Contents (click for easy navigation)

**What is Polynomial Curve Fitting?****Introduction to Polynomial Curve Fitting****Polynomial Function Basics: Brief Tutorial In MATLAB****Conclusion**

## What is Polynomial Curve Fitting?

Polynomial functions are functions which involve non-negative integer powers of x. These are inclusive of functions such as quadratic functions, cubic functions and the rest of the power progressions. The process of polynomial curve fitting is the process of constructing a mathematical function of best fit, to a series of data points, in such a way that the curve is representative of the majority of the data points present. The key is to identify a “smooth” curve of best fit. This tutorial enables the reader to determine such a curve from pre-existing data. The software used to determine this outcome is MATLAB.

## Introduction to Polynomial Curve Fitting

In
mathematical analysis, curve fitting begins with the process of matching an
output y, to a data set comprising of x variables undergoing a functional
transformation. This is represented by the general equation *y*=*f*(*x*). In all conditions, this is
the objective that is being met. With polynomial functions of orders greater
than one, curves instead of lines are generated, due to the nature of the
transformation that is being executed on the input variables in the x domain.
An example of expected visuals of polynomials is shown below.

Image credits: Google Images (Wikipedia Commons Image)

The color-coded images represent differing degrees of polynomial functions in a system, with the first order in red, the second order polynomial in green, third order in orange, and the fourth order depicted in blue. For a given data set, the objective is to match the data set with its respective curve, ensuring that all the relevant constraints have been met. With software, data fitting has been simplified, facilitating the use of geometric fitting techniques to provide the best visual fit. Facilitating the best in mathematical curve optimization tools, the smoothest result can be obtained from most statistical tools. MATLAB is very powerful in this respect.

## Polynomial Function Basics: Brief Tutorial In MATLAB

With the general theory outlined above, let us now look at the various possibilities for Polynomial Function calculations in the MATLAB R2018b user environment. A fresh command page is open below. For this exercise, we will focus on the command window to the right hand side of the screen. This is where the relevant code for the Polynomial function program will be entered. To the bottom left will be the workspace, is where the answers will be displayed, and finally a display window for the output curve will be generated by the system.

The MATLAB system initially contains a steep learning curve, but with practice, users will find that the system is actually designed to be intuitive to the end-user. The system has various functions that are designed to facilitate the execution of the appropriate curve fitting task. Since MATLAB is programming intensive, one section of this tutorial will expand on the critical codes that are applicable to Polynomial Curve Fitting. Be patient, as the actual processing itself takes less than a minute. The critical steps involve knowing what to enter into the system prior to receiving an output.

As a start, in the MATLAB user environment, the critical code that facilitates curve fitting, is the function polyfit. This function has multiple uses as is displayed below. Today’s tutorial will focus on two examples from the MATLAB workbook, that enable the user to become more familiar with the function of Polynomial Curve Fitting in the MATLAB system. The MATLAB Code Syntax for Polynomial Curve Fitting (extracted from the workbook for clarity before examples) is indicated below:

“Syntax

`p = polyfit(x,y,n)`

`[p,S] = polyfit(x,y,n)`

`[p,S,mu] = polyfit(x,y,n)`

## Description

`p`

` = polyfit(x,`

`y`

`,`

`n`

`)`

returns
the coefficients for a polynomial `p(x)`

of degree `n`

that is a best fit (in a
least-squares sense) for the data in `y`

. The coefficients in `p`

are in descending powers, and the
length of `p`

is `n+1`

*p*(*x*)=*p*1*xn*+*p*2*xn*−1+…+*pnx*+*pn*+1.

`[p,`

`S`

`] = polyfit(x,`

`y`

`,`

`n`

`)`

also
returns a structure `S`

that
can be used as an input to `polyval`

to obtain
error estimates.

`[p,S`

`,mu`

`] = polyfit(x,y`

`,n`

`)`

also returns `mu`

, which is a two-element vector with centering and scaling values. `mu(1)`

is `mean(x)`

, and `mu(2)`

is `std(x)`

. Using these values, `polyfit`

centers `x`

at zero and scales it to have unit standard deviation,

This centering and scaling transformation improves the numerical properties of both the polynomial and the fitting algorithm.”

This centering and scaling transformation improves the numerical properties of both the polynomial and the fitting algorithm.”

With these lovely details outlined, let’s jump into the calculations. As mentioned, with MATLAB, its bark is worse than its bite. Knowing the appropriate code is integral to determining the outcome for a data set. With statistical data available for a variety of applications including engineering and operational applications, the above functions will facilitate the appropriate correlations between the inputs and the outputs obtained. For simplicity, let us apply the polyfit function to a Trigonometric example from the MATLAB workbook.

## Objective: Fit Polynomial to Trigonometric Function

The question highlighted below is asking the user to generate a ten point curve using a sine function on a data set. The intervals for the points have been denoted. For clarity the code itself will be highlighted in blue, while the instructions will remain as normal.

Generate 10
points equally spaced along a sine curve in the interval `[0,4*pi]`

.

x = linspace(0,4*pi,10);

y = sin(x);

Use `polyfit`

to fit a 7th-degree polynomial to
the points.

p = polyfit(x,y,7);

Evaluate the polynomial on a finer grid and plot the results.

x1 = linspace(0,4*pi);

y1 = polyval(p,x1);

figure

plot(x,y,'o')

hold on

plot(x1,y1)

hold off

Extracting the relevant code into MATLAB, the code entry into the MATLAB system is as follows:

The code elements factor in all the relevant requirements of the question. The x and y functions as well as their line spacings are identified by the input constraints. Once the code is entered, the following is the system’s output:

The result is a beautiful, sine curve as desired by the instructions given. With appropriate tweaking, the quality of the curve can be adjusted by the user, in order to facilitate the curve quality that is desired by the nature of the project under study.

## Example Two: Polyfit MATLAB

The MATLAB system is chock full of polynomial examples that the user can attempt. This second example focuses on vector creation. Just like in the previous example, the critical code will be entered into MATLAB. Highlighting the relevant code in blue:

OBJECTIVE: Create a vector of 5 equally spaced points in the interval `[0,1]`

, and evaluate

at those points.

x = linspace(0,1,5);

y = 1./(1+x);

Fit a polynomial of degree 4 to the 5
points. In general, for `n`

points,
you can fit a polynomial of degree `n-1`

to exactly pass through the points.

p = polyfit(x,y,4);

Evaluate the original function and the polynomial fit on a finer grid of points between 0 and 2.

x1 = linspace(0,2);

y1 = 1./(1+x1);

f1 = polyval(p,x1);

Plot the function values and the
polynomial fit in the wider interval `[0,2]`

, with the points used to obtain the
polynomial fit highlighted as circles. The polynomial fit is good in the
original `[0,1]`

interval, but quickly diverges
from the fitted function outside of that interval.

figure

plot(x,y,'o')

hold on

plot(x1,y1)

plot(x1,f1,'r--')

legend('y','y1','f1')

The following is the code entry into the MATLAB System:

The system output is shown below:

With the variety of Polyfit functions available, the examples in today’s tutorial focused solely on the simple polyfit function. If you so desire, and feel the need to generate more sophisticated curves, refer back to the early codes identified in the pre-amble to the discussions. As with all software, MATLAB does require a little sweat equity, but eventually the desired outcomes will be achieved. Happy coding!

## Conclusion

From the computations and detailed theory and background above, it can easily be identified that MATLAB R2018b is a powerful simulation tool. The system does require specialized knowledge in order to properly code and navigate the system, and has an initially steep learning curve. Fortunately, there are plenty of support tools and tutorials such as ours that are available online, that will facilitate a smooth transition to the world of MATLAB. As gamification is on the rise, users will enjoy the challenge that the system will provide in order to help them achieve in a fun and interactive manner the means via which their systems can be modeled before actual computation. IF statement computations are ubiquitous, and they can only help us to advance science and technology. Use the tutorial above to help with your scientific and engineering needs.

Tandose Sambo is a Chemical Process Engineer, with a focus on improving process efficiency via operational improvements. Six-Sigma certified, and with a Design-focus and Data Analytics interest, she is a driven growing entrepreneur, with the intention to optimize industrial and business process operations. Her interests include sharing time with family and travelling.