Next: 6. Real programming
Up: 5. Data analysis
Previous: 5.2 Linear regression
  Contents
MATLAB has built in routines for fitting functions to data. The easiest
to use is polyfit. Go to the index in the help menu and look up
polyfit and see how it works. Then try the following.
% Simulate position vs. time data for a rolling ball
close all; clear all;
randn('state',0); % Reset the random number generator
x = 1:9; % define the intervals for taking measurments
vox = 0.5; % initial velocity in the x direction
t = x/vox; % compute t for ideal case
t = t+.5*randn([size(x) 1]); % add some noise
plot(x,t,'o') % plot the data and add labels
ylabel('time (sec)')
xlabel('position (m)')
title('Time vs. position for a rolling ball')
axis([0 9 0 20])
hold on % keep the first graph up while we plot the fitted line
% Fit a line thru the data and plot the result over the data plot
temp = polyfit(x,t,1); % least squares fitting to a line
a1 = temp(2) % y-intercept of the fitted line
a2 = temp(1) % slope of fitted lines
fit = a1+a2*x;
plot(x,fit)
axis([0 9 0 20])
hold on
Rerun this script several times after commenting out the third line where
the random generator is reinitialized. Count how many data points lie above
the line and how many lie below each time. What do you find?
Do you suppose we can come up with a function that fits even better than
this straight line? What about a quadratic? Or an eighth order polynomial?
Since these functions are more flexible (have more parameters), they should
be able to fit the data with a smaller
. Run the previous script
again if the figure window isn't still open and then try an eighth order
polynomial fit.
% Try a higher order fit
a = polyfit(x,t,8);
new_x = 0:.1:10;
new_t = polyval(a,new_x);
plot(new_x,new_t)
axis([0 9 0 20])
As you can see this new function passes exactly through each data point and
therefore
. Which of the curves do you think best represents the
physics of the situation the best? Why? This is a simple example of
how the scientist needs to bring a little common sense and intuition to
problems of fitting and statistical analysis.
Next: 6. Real programming
Up: 5. Data analysis
Previous: 5.2 Linear regression
  Contents
Gus Hart
2005-01-28