An interactive introduction to MATLAB

(Jeff_L) #1
2.2curve-fitting 25

2.2 Curve-fitting


MATLABprovides a number of powerful options for fitting curves and adding
trend-lines to data. The Basic Fitting Graphical User Interface (GUI) can
be selected from Figure Windows by selecting Basic fitting from the Tools
menu, and offers common curve-fitting options for 2dplots. More advanced
functionality, including 3dfits, can be accessed from the Curve Fitting Toolbox
using tools such ascftool(for curve fitting) andsftool(for surface fitting)∗.

Basic Curve-fitting


(http://www.eng.ed.ac.uk/teaching/courses/matlab/unit02/basic-curve-
fitting.shtml)
An alternative to the Basic Fitting GUI are the functionspolyfitand
polyvalwhich can be used to do basic curve-fitting programmatically. List-
ing 2.3 demonstrates howpolyfitcan be used to fit a polynomial to a
data-set.
Listing 2.3: Syntax ofpolyfitcommand
1 coeff = polyfit(xdata,ydata,n);


Comments:


  • coeffis a vector containing the coefficients for the polynomial of best fit,
    xdataandydataare vectors containing the independent and dependent
    variables, andndenotes the degree of the polynomial to be fitted.


After usingpolyfityou can use thepolyvalfunction to evaluate the poly-
nomial of best fit, given by the set of coefficientscoeff, at specific values of
your data. This creates a vector of points of the fitted data,y_fit. Listing 2.4
and Figure 7 demonstrate the use of both thepolyfitandpolyvalfunctions.
The data used for fitting can be downloaded (linear_fitdata.mat) and upon
double-clicking the
.mat_ file, the data will be loaded intoMATLABand
assigned to the variablesxandy. This data is best fitted using a linear or
straight-line fit.
Listing 2.4: Usingpolyfitandpolyvalfor curve-fitting
1 >> coeff = polyfit(x,y,1);
2 >> y_fit = polyval(coeff,x);
3 >> plot(x,y,'r+',x,y_fit), grid on, xlabel('x−data'), ...
4 ylabel('y−data'), title('Basic curve−fitting'), ...
5 legend('Original data','Line of best fit','Location','SouthEast')


∗Only basic curve-fitting will be covered in this course.

Free download pdf