Search Contact information
University of Cambridge Home Department of Engineering
University of Cambridge >  Engineering Department >  computing help >  programs >  matlab

Matlab - curve fitting

Lines

lsline superimposes the least squares line on each line object.

Polynomials

polyfit finds the coefficients of a best-fit polynomial of any required degree. The following tries to fit a degree 5 polynomial to a sin curve

 x=1:10;
 y=sin(x);
 [P,S] = polyfit(x,y,5); 
 yfit= polyval(P,x);
 %Now compare y with yfit
 plot(x,y,x,yfit);

If you want to force the best-fit line to pass through certain points, look at MatlabCentral's Polynomial Fitting with Added Constraints.

Arbitrary Functions

If you know the form of the required function you can use fminsearch to find the best coefficients. Suppose that you think that some data should conform to a relation of the form a*x+b*sin(x)+c. To be able to use fminsearch you need to write a matlab function that for given values of a, b and c, calculates the square of the disparity. Its first argument is a vector of coefficients, its last argument is a vector of the given data values. The other arguments (in this case, just one) are vectors of free variables. You can put this function into its own file or (as here) make it into a subfunction. If you put the following code into a file called fitting.m, then run it, you should see how good to fit is.
 function fitting
 x=1:10;
 y=sin(x);
 bestcoeffs=fminsearch(@fun,[1 1 1],[],x,y);
 yfit=bestcoeffs(1)*x +bestcoeffs(2)*sin(x) +  bestcoeffs(3);
 %Now compare y with yfit
 plot(x,y,x,yfit);

 function out=fun(coeff,X,Y)
 a = coeff(1);
 b = coeff(2);
 c = coeff(3);
 Y_fun = a .* X + b .* sin(X)+c;
 DIFF = Y_fun - Y; 
 SQ_DIFF = DIFF.^2;

 out = sum(SQ_DIFF);
Note that the [1 1 1] argument to fminsearch provides the starting values for a, b and c. The choice of starting values can affect the speed of the search.

An example of fitting a function of 2 values is in Mathworks' Solution Search (Solution 1484)

Surfaces

Available solutions depend on the toolboxes you have, and why you want the equation of the surface.
© Cambridge University Engineering Dept
Information provided by Tim Love (tpl)
Last updated: August 2006