% eda04_10
% reads in noisy, linear data from file
% and computes and plots predicted data
% using least-squares estimate of intercept
% and slope, m1 and m2

% laod file of noisy data
T = load('linedata01.txt');

% now independently name the two columns of data
x = T(:,1);
dobs = T(:,2);
N = length(dobs);
M=2;

% plot data as black circles
figure(1);
clf;
set(gca,'LineWidth',2);
axis([-6 6 -15 15]);
hold on;
plot(x,dobs,'ko','LineWidth',2);
xlabel('x');
ylabel('d');
title( 'plot of linedata01.txt' );

% data kernel
G=zeros(N,M);
G(:,1)=1;
G(:,2)=x;

% least squares estimate
mest = (G'*G)\(G'*dobs);
mest1=mest(1);
mest2=mest(2);
mest1
mest2

% compute and plot predicted data
dpre = G*mest;
plot(x,dpre,'k-','LineWidth',2);

% compute and plot error
e=dobs-dpre;
for i = [1:N]
    y1 = dobs(i);
    y2 = dobs(i)-e(i);
    plot( [x(i), x(i)], [y1, y2], 'k:', 'LineWidth', 2 );
end

% compute total error
E = e'*e;
E

% estimate of the variance of the data
sigmad2 = E/(N-M);
sigmad = sqrt(sigmad2);
sigmad

% estimate of the cariance of the estimates model parameters'
Cm = sigmad2*inv(G'*G);
sigmam1 = sqrt(Cm(1,1));
sigmam2 = sqrt(Cm(2,2));
sigmam12 = Cm(1,2);

sigmam1
sigmam2
sigmam12