previous: read data file
next: define/plot functions

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",{Number,Number}];
Fit[ xy, {x^5, x^4, x^3, x^2, x^1, 1}, x]

(2)
xy = ReadList["xyN.dat",{Number,Number}];
Needs["Statistics`NonlinearFit`"]
YofX[x_] = a Exp[b x] Sin[c x + d]
initialguesses = {{a,0.5},
    {b,-0.5},{c,1.5},{d,0.5}}
ft = NonlinearFit[xy, YofX[x], x,
    initialguesses]
Plot[ft, {x,0,20}];

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

PRO YofX, x, A, f   (first define the nonlinear function)
    f = A[0] * exp(A[1] * x) * sin(A[2]*x + A[3])
END

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