\maketitle
\section{Introduction}
Curve fitting is one of the most common analytical tasks you will
perform during Junior Lab.  Students are welcome to utilize any set of
routines for curve fitting as long as the standards for reporting
results, identified in this and other Junior Lab
documents, are met.

This short guide is designed to get you started using Matlab, a
commercial product available on the Win-Athena computer cluster in
Junior Lab.  {\bf Matlab is free for MIT students wishing to run it on
their own computers; see {\tt web.mit.edu/matlab/www} and is also
available on any Athena workstation at the Institute}.  \footnote{While Matlab
is the default Junior Lab solution, some students prefer to use
alternative mathematics packages (e.g. Gnuplot, Maple, Mathematica or LabVIEW).
The only requirement is a solid understanding of the underlying
algorithm and mathematics, detailed in many places, most notably
Bevington and Robinson (2003), Reference
\cite{bevington}.  It is a good idea to have this reference at your
side while doing data analysis as you will be continually referring to
it throughout your work!}

\section{Starting Matlab}

\begin{enumerate}
\item From the Athena prompt, attach the Matlab locker (you can also add this to you .cshrc.mine file to have it automatically attached at login):
\begin{verbatim}  % add matlab
\end{verbatim}
\item Open Matlab into a new window:
\begin{verbatim}  % matlab &
\end{verbatim}
\end{enumerate}
Once it has finished loading, it will present you with the Matlab
prompt: {\tt >>}.  From this prompt you can execute any of the Matlab
commands or run a Matlab script.  To run a script, first make sure it
ends in {\tt .m} and resides in your {\tt matlab} directory and
then simply type the name at the prompt (without the {\tt .m}):
\begin{verbatim}  >> myscript
\end{verbatim}

\section{Using Matlab Scripts}
One very powerful yet simple way to utilize Matlab is to use scripts.
Scripts are simply text files that contain a series of Matlab
commands.  The entire process of curve fitting will require at least a
handful of commands so it is useful to have them all in a single
script.  Once you have this script you can return to it later, repeat
your fit, make modifications, etc. without having to retype all of the
commands.

If you plan to use Matlab scripts, it's a good idea to create a
`matlab' directory in your home directory.  You can do this by typing:

\begin{verbatim}
  % cd ~; mkdir matlab
\end{verbatim}
You should save any Matlab scripts that you write in this directory.
You can use emacs (or any other text editor) to create and edit Matlab
scripts.  For example, to create a new script called {\tt myscript.m}
type:
\begin{verbatim}  % >> edit myscript.m
\end{verbatim}
Notice the ``{\tt .m}'' extension on the script.  All Matlab scripts
must end in ``{\tt .m}'' in order to execute correctly.  The edit
command opens up a text editor within Matlab.


\section{Using the Junior Lab Fitting Template Script}
To accommodate quick and easy fitting for Matlab beginners, we have
created a script that you can use as a template for fitting.  This
script is available from the Matlab section of the Junior Lab website.
 You should start by downloading all four of the Matlab `.m' files at
 \url{http://web.mit.edu.8.13/matlab} to a newly created directory on
 your Win-Athena or Athena lockers.  These include:
\begin{itemize}
\item fittemplate07.m (the base fitting template)
\item fitlin.m    (for fitting linear functions)
\item levmar.m    (for fitting non-linear functions)
\item gauss3.dat  (a sample data set used in the base fitting template)
\end{itemize}

Before examining the script in detail, try simply running it by typing (within Matlab):
\begin{verbatim}
>> fittemplate
\end{verbatim}
This script performs the nonlinear fit and produces a publication
quality graphic, already for use within a Junior Lab written summary
or in an oral exam presentation!!! As you can see, a Matlab scripts
are is a very powerful tool with which you will want to become very
familiar!  By encapsulating all the pertinent information into a
`script' it is very easy to return at a later date to recreate the fit
or to apply the same script to a new data set.  It is a good idea to
get into the habit of adding comments to each new script and to use
`intuitive' naming schemes for your filenames.

The basic procedure for
using this fitting script is outlined as follows:
\begin{enumerate}
\item
{\bf Open} the script in Matlab using the `edit' command.
\item
{\bf Modify} the script such that it:
\begin{enumerate}
\item
Loads data from an arbitrary space delimited file into the vectors
{\tt x} and {\tt y}
\item
Assigns the appropriate errors (this is the hard part!)
\item
Contains the functional form that you want to fit (consider adding
baseline terms for real data containing noise and insrumental offsets!)
\item
Plots figures with labels appropriate for your data
\end{enumerate}
\item
{\bf Save} the file with a new name, keeping the .m extension
\item
Run the script!
\item
Matlab will {\bf fit} your data, output the information relevant to
the fit, and {\bf plot} (1) the fitted curve on top of the original
data and (2) the residuals.
\end{enumerate}

We will now go through this process in detail.

\subsection{Non-Linear Least Squares Example}
In developing this guide, we have used the Statistics Reference
Dataset ``Gauss3'' available from the National Institute of Standards
in Technology at
\url{http://www.itl.nist.gov/div898/strd/nls/data/gauss3.shtml}.  Since NIST
has kindly provided certified values for this dataset, it is an
excellent test case for checking the acceptability of alternative data
fitting products.  You should always test your fitting algorithms on a
certified data set to test it's accuracy before applying it to your
own Junior Lab data!

The sample dataset, entitled ``gauss3.dat'' (downloaded previously
from the Matlab section of the Junior Lab web page), consists of two poorly
resolved Gaussian peaks on a decaying exponential background and must
be fit using using a general (nonlinear) custom model.  It has
normally distributed zero-mean noise with a variance of 6.25.

Here we step through the process of modifying the template script to
fit this `known' dataset.  Note also that the any and all parts of the
``template script'' may be entered directly from the matlab command
line.  This is useful when diagnosing script generated errors.

\begin{enumerate}
\item {\bf Open the script in the Matlab editor window}
\begin{verbatim} % >> edit fittemplate07.m
\end{verbatim}

\item {\bf Modify the script such that it:}
\begin{enumerate}
\item
Loads data from your file into the vectors {\tt x} and {\tt y}.

\parindent .2 in {\footnotesize Currently the script is set up to load
  the simulated data file called `gauss3.dat' described earlier.  It
  can be changed to load whatever dataset name you require:
\begin{verbatim}
   load gauss3;
\end{verbatim}
The result of a {\tt load} command on a tab-delimited text file is a
single ``matrix'' variable with the name gauss3 (250 rows x 2 col).
The next lines in the script assign values to the {\tt x} and {\tt y}
vectors from this parent matrix.
\begin{verbatim}
   x=gauss3(:,1);
   y=gauss3(:,2);
\end{verbatim}
(Note that this syntax utilizes the entire data set in the vector
definitions.  By placing indices on either side of the colon, a subset
of the entire data file may be selected for fitting.)}
\item
Assigns the appropriate errors

{\footnotesize
You will want to create a vector of error values.  While the error
values may or may not be uniform, the error vector must be the same
size (length) as the vectors {\tt x} and {\tt y}.

In the case of gauss3, we have a constant variance of 6.25 so we can assign the weights with the commands:
\begin{verbatim}
   sig=ones(size(x))*sqrt(6.25);
\end{verbatim}
which creates a weighting vector of the same size as the vector {\tt
x} with a constant value of one over 2.5.  See Reference
\cite{bevington} for more information on weighting vectors.

{\bf Note:} Since there are several different
ways you could assign values to the error vector {\tt sig}, the script
includes several different assignment statements that cover a few
cases.  Once you have chosen one and modified it for the fit you are
doing, you will need to \emph{comment out} the other lines that assign
values to sigma.  To comment something out, simply put a `{\tt \%}' in
front of it.  {\LaTeX} regards any thing following a `{\tt \%}' as a
comment and does not interpret it.  You'll notice that the template is heavily commented to explain what the commands are doing. }
\item
Contains the functional form that you want to fit

\parindent .2 in{\footnotesize
The two general classes of functions that you will fit in Junior Lab
are simple straight lines that can be solved in closed form and
arbitrary functions which must be solved iteratively.  The template
script invokes the functions {\tt fitlin.m} and {\tt levmar.m}
for these two cases respectively.  Each of these cases is handled
slightly differently within the fitting template.  We will discuss
each separately.

\noindent {\bf Arbitrary Functions}

When fitting an arbitrary non-linear function (e.g. a gaussian or
exponential function), you will need to specify the following:
\begin{itemize}
\item The {\tt x} and {\tt y} vectors of your data,
\item A vector {\tt sig} containing the uncertainties of each data point,
\item The functional form you want to fit to the data,
\item An vector with an initial guess of the parameters.
\end{itemize}

The function {\tt levmar.m} performs the fit by iteratively
searching for the minimum value of the Chi-Square ($\chi^2$) using
the Levenberg-Marquardt algorithm detailed in Bevington and Robinson
(2003).  Each iteration varies the parameter by a certain stepsize
to determine the minimum to within a certain tolerance (the variable
`chicut' in the matlab script).  Thus, your fit is more likely to be
fast and accurate with a carefully chosen set of initial parameters.
Additionally, being able to estimate parameters quickly from graphs
of data is an important skill that will serve you well.

It is also possible for such a fitting process to converge on a
local minimum in $\chi^2$ space that does not represent the best
fit.  If this is happening to you, you can modify both the
`stepsize' and the tolerance `chicut' used by {\tt levmar.m}.
Both of these parameters are labeled within the function.

\noindent {\bf Straight Lines}

When fitting a straight line, simply comment out the line that
specifies the starting parameters {\tt a0} and the line that calls
{\tt levmar} within the script.  Then, simply uncomment the line
that calls {\tt fitlin}.  Notice that for a straight-line fit, you
only need to specify the {\tt x} and {\tt y} vectors of your data
and the {\tt sig} vector containing the error values.  You do not
need to specify starting parameters.  }
\item
Plots figures with labels appropriate for your data

\parindent .2 in
{\footnotesize Running the script will automatically generate plots
for you.  You'll need to make sure these graphs display the data you
want with the correct labels.

Currently the script will generate one figure that is split into two
sections.  The top section will contain the fitted curve plotted on
top of your data points with errorbars.  The bottom section will
contain the residuals of your fit.

The commands {\tt `title', `xlabel'}, and {\tt `ylabel'} label the
title, x axis and y-axis of the graph respectively.  Right now the
script just gives them generic titles.  Make sure to modify these
lines to give your graph meaningful labels with units.}
\end{enumerate}
\item
{\bf Save the file with a new name, keeping the .m extension.}  \\ Be
sure to save it with a \emph{different} filename so that the template
script will be left intact for your next fitting adventure.
\item
\parindent .2 in {\bf Open Matlab and run the script.}  \\ If the
script is saved in your matlab directory, you should be able to run it
simply by typing in the name at the Matlab prompt (without the the
{\tt .m}).  You may need to change directories if the file is stored
elsewhere.  Matlab has the same directory navigation commands as
Athena such as {\tt `ls', `cd'}, {\tt `pwd'}, etc.
\item
{\bf Matlab will fit your data, output the information relevant to the
fit, and plot (1) the fitted curve on top of the original data and (2)
the residuals.}

\end{enumerate}

The script is currently setup to output the values determined for the
coefficients and their errors as well as the reduced
chi-square\footnote{This is simply the $\chi^2$ (a statistic used
frequently by physicists and in Bevington) divided by the DFE (Error
Degrees of Freedom). The DFE is equal to the number of data points
minus the number of fitted coefficients.}  $(\chi^2_{\nu-1})$ of the
fit.  The script causes these particular values to be output because
they are declared with no semi-colon.  In general, a semi-colon at the
end of a Matlab command suppresses the output of the command.


\section{Generating Presentation Graphics}
 Figure \ref{fig:typical-fit-plot} demonstrates a typical graphic you
 might create for an oral presentation or written summary.
\begin{figure}[h]
  \includegraphics[width=8cm]{typical-fit-plot}
\caption{This is an example of a basic figure for Junior Lab
notebooks, presentations and written summaries. {\bf You should check
with your individual section instructor for explicit instructions on
how to prepare figures for presentation within your section.}
%The best-fit parameters (at the 68.2\% or 1-$\sigma$ confidence level)
%are: a=98.94$\pm$0.53, a1=100.7$\pm$0.8, a2=73.71$\pm$1.21,
%b=0.01095$\pm$0.00012, b1=111.6$\pm$0.4, b2=147.8$\pm$0.4,
%c1=23.3$\pm$0.37, c2=19.67$\pm$0.38.
\label{fig:typical-fit-plot}}
\end{figure}
The fitting template script is already configured to generate graphs
of your data, the fitted curve and the residuals.  However, as
previously mentioned you will need to customize the titles and axis
labels so they are relavent and meaningful to your graph.  In
addition, you may also wish to annotate your graph with additional
information.  {\bf The fittemplate07.m script has several examples of how to
automatically place properly formatted fit results within a plot.}  You
can do this graphically with the tools provided in the graph window or
by using the {\tt `text'} command within the script.  To use the {\tt
`text'} command you simply specify $x$ and $y$ coordinates and the
string you wish to appear.  The coordinates should be in the same
units of the graph to which they refer.  For example:
\begin{verbatim}
   text(18,5,'y(x) = ae^{-bx}+a_1e^{-((x-b_1)/
        c_1)^2}+a_2e^{-((x-b_2)/c_2)^2})
\end{verbatim}
would provide an appropriate label for the gauss3 graph in the lower
left-hand corner.  Notice also that Matlab can interpret latex
formating to display Greek characters, superscripts, and subscripts.

When you have your graphs just the way you (and your section
instructor!) want them (a completed graph might look like Figure
\ref{fig:typical-fit-plot}) , you can output them for use in your lab
notebooks, written summaries, and oral presentations.  If you simply
want printouts of your graphs for your notebooks, select {\tt
`Print...'} from the {\tt `File'} menu and make sure the correct
printer is specified.

You can save your graphic in Portable Document Format (PDF) for easy
inclusion into {\LaTeX} generated reports and oral presentations.

\section{Getting started with Matlab at MIT}

Exhaustive details about running Matlab can be found at: {\tt
web.mit.edu/matlab/www}.  Throughout the year, and especially at the
beginning of the academic year, Athena Minicourses on Matlab are
offered.  If you can't make one of these (or in addition), web based
training for Matlab also exists. See the Junior Lab web page for
details. Finally and perhaps your best resource is simply to talk to
friends and classmates; many of them have a great deal of Matlab
experience!

\begin{thebibliography}{99}

\bibitem{bevington} Bevington, P.R., and D.K. Robinson, \textsl{Data
Reduction and Error Analysis for the Physical Sciences, 3rd
Ed.},WCB/McGraw-Hill, Boston, 2003
\bibitem{levenberg} Levenberg, K., ``A Method for the Solution of Certain Problems in Least Squares'', \textsl{Quart. Appl. Math}, Vol. 2, pp. 164-168, 1944
\bibitem{marquardt} Marquardt, D., ``An algorithm for Least Squares Estimation of Nonlinear Parameters'', \textsl{SIAM J. Appl. Math}, Vol. 11, pp. 431-441, 1963
\bibitem{branch} Branch, M.A., T.F. Coleman, and Y. Li, ``A Subspace,
Interior, and Conjugate Gradient Method for Large-Scale
Bound-Constrained Minimization Problems'', \textsl{SIAM Journal on
Scientific Computing}, Vol. 21, Number 1, pp. 1-23, 1999
\bibitem{hecht} Hecht, E., \textsl{Optics: 4th Edition},Addison-Wesley,
2002
\bibitem{kittel} Kittel, C., and Kroemer, H., \textsl{Thermal Physics,
2nd Ed.}, W.H. Freeman, 1980
\end{thebibliography}
