% Programming and Numerical Methods
% MSc in Computational and Applied Physics

% Code 4: Linear Regression
% A. Meseguer (2007)

  clear all 
  close all

% Data 
% We first initialize a vector of data and a vector 
% of random perturbations that fakes typical experimental
% data scattering
   x = linspace(0,1,100)' ; 
   noise = 0.1*rand(100,1) - 0.05 ; 

% We try to find the slope and vertical interception coordinate
% of:  
  A = 3.5 % Exact vertical interception
  B = 4.0 % Exact slope 
  y = A + B*x + noise ;  

  f0 = 1 + 0*x ; f1 = x ;
  den = (f1'*f1)*(f0'*f0) - (f0'*f1)^2 ;
  a0 = ((y'*f0)*(f1'*f1)-(y'*f1)*(f1'*f0))/den ;
  a1 = ((y'*f1)*(f0'*f0)-(y'*f0)*(f1'*f0))/den ;

% We plot the exact curve
  plot(x,A + B*x,'-k') ; hold on

% And the linear regression points
  plot(x,y,'or')
