Department of Applied Mathematics at the University of Colorado at Boulder
University of Colorado at Boulder Search A to Z Campus Map University of Colorado at BoulderCU Search Links
Print this page

Fit Polynomial

13: Fitting a function to x-y data points

Read in some x-y data and then find a least-squares fit to the data as a linear combination of given functions, or as a nonlinear function.

1. Read in arrays x and y from file xyL.dat, and find the best 5th-degree polynomial fit

2. Read in arrays x and y from file xyN.dat, and find the best fit to y(x) = a exp(bx) sin(cx + d)

Mathematica:

(1)
xy = ReadList["xyL.dat",];
Fit[ xy, , x]
(2)
xy = ReadList["xyN.dat",];
Needs["Statistics`NonlinearFit`"]
YofX[x_] = a Exp[b x] Sin[c x + d]
initialguesses = ,
    ,,}
ft = NonlinearFit[xy, YofX[x], x,
    initialguesses]
Plot[ft, ];

 

Matlab:

(1)
load xyL.dat     % assuming OK format
a = polyfit(xyl(:,1),xyL(:,2),5)

(2)

Maple:

xxx

IDL:

(1) xy = fltarr(2,21)
OpenR, 19, 'xyL.dat'
ReadF, 19, xy
Close, 19
x=reform(xy[0,*]) & y=reform(xy[1,*])
print, Poly_Fit(x,y,5)
(2)
xy = fltarr(2,41)
OpenR, 23, 'xyN.dat'
ReadF, 23, xy
Close, 23
  (first define the nonlinear function)
    f = A[0] * exp(A[1] * x) * sin(A[2]*x + A[3])
END

 

PRO YofX, x, A, f

x=reform(xy[0,*]) & y=reform(xy[1,*])
A = [ 0.5, -0.5, 1.5, 0.5 ]
w = x * 0.0 + 1.0
fit = CurveFit(x,y,w,A,sd, $
    Function_Name='YofX', /noderivative)
print, A   &   plot,x,fit