% ==========================================================================
% leastsq.m -- Compute least squares polynomial fit on experimental data 
%
% Experiment : x = displacement of spring (cm).  
%              f = force in spring (N).  
%
% Least squares fit : p(x) = a + b.x + c.x^2  
% ==========================================================================

% Store force-displacement relationship in matrix "data"

data = [ 5.0    0.0;
         5.5   47.5;
         6.0   90.0;
         6.5  127.5;
         7.0  160.0;
         7.5  187.5;
         8.0  210.0 ];

% Compute terms in least squares matrix and right-hand vector

N = 7;
sumx   = sum(data(:,1));
sumy   = sum(data(:,2));
sumxy  = sum(data(:,1).*data(:,2));

sumx2  = sum(data(:,1).*data(:,1));
sumx2y = sum(data(:,1).*data(:,1).*data(:,2));
sumx3  = sum(data(:,1).*data(:,1).*data(:,1));
sumx4  = sum(data(:,1).*data(:,1).*data(:,1).*data(:,1));

A = [      N   sumx   sumx2
        sumx  sumx2   sumx3
       sumx2  sumx3   sumx4 ]

B = [ sumy; sumxy; sumx2y]

% Compute and print constants a,b,c

Coefficients = A\B

% ============================================================
% the end!
