Math 371 - Alexiades

Least Squares Fitting in Matlab and in Gnuplot
Given a file "data" containing (x, y) pairs of data points, e.g. U.S. Census population,
we may want to predict the population in the future.
Can use Matlab or Python or Gnuplot to fit to some model and extrapolate to future years.
First, let's plot the points to see the shape.
Easiest via Gnuplot:   gnuplot> plot "data" or, better looking: plot "data" w lines lt 1 lw 4
What does it resemble ? perhaps a parabola? a cubic? an exponential?

1. Least Squares fitting in Matlab / Octave
  a. Read the 'data' file into a matrix (NOTE: file must be clean, only 2 columns of (x, y) data, no comment lines):
      >> load data
  b. Extract the 1st column of 'data' to a vector T, and the 2nd column to a vector P:
      T = data(:,1);   P = data(:,2);
      plot(T, P, '-o');

  c. Use polyfit to fit the points to a quadratic q(t):
      [q Sq] = polyfit(T, P, 2);
  d. Use polyval to evaluate q(t) at T. Write it to Q:
      Q = polyval(q, T);
  e. Plot the points and the quadratic on the same plot:
      plot(T, P,'o', T, Q);
  f. Similarly, fit the points to a cubic:
      [c Sc]= polyfit(T, P, 3);   C = polyval(c, T);
  g. Plot the points, the quadratic, and the cubic on the same plot:
      plot(T, P,'o', T, Q, '->', T, C, '--*');
      title('data & quadratic fit and cubic fit');

  h. What does each fit predict for the population in 2023 ? in 2030 ?
      q2030 = polyval(q, 2030);  c2030 = polyval(c, 2030);


2. Least Squares fitting in Gnuplot

  a. To fit a function f(x) to data points stored in a file "data":
    - define f(x), e.g. f2(x) = a + b*x + c*x*x (fit parameters: a,b,c)
    - do the fitting: fit f2(x) 'data' via a, b, c
    - Record the parameter values you get, and the rms of residuals.
    - plot them: plot "data" w points lt -1 lw 4, f2(x) w lines lt 1 lw 3
  b. Fit to a cubic: f3(x) = a + b*x + c*x*x + d*x*x*x
      fit f3(x) 'data' via a,b,c,d
    - Record the parameter values you get, and the rms of residuals.