%% Matlab script for least square linear approximation
%% This script shows the approximation with a second degree polynom
%% Written by Philippe Lucidarme
%% http://www.lucidarme.me
close all;
clear all;
clc;

% Set the coefficients a, b and c (y=ax²+bx+c)
a=0.8;
b=-5;
c=-20;
Noise=10;

% Create a set of points with normal distribution
X=[-10:0.2:10];
Y=a*X.*X + b*X + c + Noise*randn(1,size(X,2));

% Prepare matrices
A=[ (X.*X)' ,  X' , ones(size(X,2),1) ];
B=Y';

% Least square approximation
x=pinv(A)*B;


% Display result
plot (X,Y,'.');
hold on;
plot (X,A*x,'g');
grid on;
xlabel ('x');
ylabel ('y');
legend ('Input data','Approximation');
title ('Least square approximation');


