Fitting and error analysis in Matlab
Matlab has been installed in the computers in senior lab and in Room 310, ST I. A very
basic introduction to Matlab is given in Appendix B of the courses textbook (Melissinos
and Napolitano). Matlab also has quite a good help navigator built into it, which includes
tutorials. Below is given a bare-bones guide to error analysis and fitting using Matlab.
Error bars in plotting
For plotting y error bars you can use the built in function, errorbar(xdata, ydata,
lower_errorbar, upper_errorbar), which both plots the data and the errorbars. If in
addition you would like to plot x error bars or horizontal error bars, you can download
and use the function file herrorbar from http://www.mathworks.com/matlabcentral/ . In
order to get both x and y error bars on the same graph, use hold on after applying the first
set of error bars.
Fitting to a polynomial when the data points are equally weighted
As explained in the textbook, in order to fit a dataset =(xdata, ydata) to a polynomial of
degree n one can use [p, S] =polyfit(xdata, ydata, n), where p is the vector that contains
the coefficient of the polynomial, and S is a structure for use with polyval to obtain error
estimates or predictions. In order to generate the fit-data, yfit, and to find the error in the
fitting parameters, delta_p, one uses [yfit, delta_p] =polyval(p, xdata, S).
Fitting to a line when the data points are not equally weighted
Examples of unweighted and weighted fits to a line are given in your textbook on page
359. As shown in this example, when you have unequally weighted data points one can
use a function called linreg, which can be downloaded from
http://www.mathworks.com/matlabcentral/ .
Fitting to a general function
Fitting to a general function can be somewhat involved, but a good introduction to this is
given in sections 10.3 and 10.4 of the text. In the MIT OpenCouseWare for their J unior
Lab, they have several nice matlab fitting routines that are quite well-commented. You
can download these files from:
http://ocw.mit.edu/OcwWeb/Physics/8-13-14Fall-2004-Spring-2005/StudyMaterials/index.htm
The key files to download are 1) newfittemplate.m, which demonstrates how to load the
data, call the fitting routines, and plot the data, and 2) fitlin.m or fitnonlin.m depending
on whether you are fitting your data to a straight line or whether you are fitting your data
to a non-linear function. If you are fitting you data to a non-linear function, you will
have to create a separate function file. An example of such a function file is given on the
MIT website for a Gaussian function, g3function.m.