% Curve-Fitting
% Suppose we have a set of data and we want to fit that data to a curve, minimizing the error between the curve and the data. For example, we might have a data set such as:

clear all
x=[68 69 69.5 71.25];
y=[5.5 7.5 9 10.5];
plot(x,y,'o','LineWidth',2)
xlabel('x')
ylabel('y')
set(gca,'FontSize',20)

% The Matlab functions polyfit and polyval will fit a polynomial to this data. Polyfit determines the coefficients of the polynomial that best fits the data and polyval helps us evaluate that polynomial at certain values of x. The process is as follows:

coefs=polyfit(x,y,1);
xfit=67:0.01:73;
ylinefit=polyval(coefs,xfit);
coefs=polyfit(x,y,2);
yfit=polyval(coefs,xfit);
plot(x,y,'o',xfit,ylinefit,xfit,yfit,'LineWidth',2)
xlabel('x')
lgd=legend('data', 'first order fit', 'second order fit');
lgd.FontSize = 14; lgd.Location='northwest';
set(gca,'FontSize',20)

% © James Blanchard, University of Wisconsin-Madison, blanchard@engr.wisc.edu