clear all;

%zählrohr charakteristik
%daten einlesen

d=load('charakter.dat.csv');
U=d(:,1);
n1=d(:,2);
n2=d(:,3);
n3=d(:,4);

%korrektur:
k=[1:numel(n1)];
gt(k)=1./(1 - n1(k).*(1.6.*10.^(-004)));
n1=n1.*gt';

gt(k)=1./(1 - n2(k).*(1.6.*10.^(-004)));
n2=n2.*gt';

gt(k)=1./(1 - n3(k).*(1.6.*10.^(-004)));
n3=n3.*gt';


n=(n1+n2+n3)/3;
dn=sqrt(1/3*((n-n1).^2 + (n-n2).^2 + (n-n3).^2));

%Fit
	lin=[11:numel(n)];
	%Kurvenfit Pld = a + b * Id
	X=[ones(size(U(lin))),U(lin)];
	k=X\n(lin);
	a=k(1);
	b=k(2);
	%Fehler
    gn = 1./dn.^2;
    alpha11=sum(gn(lin));
	alpha12=sum(gn(lin).*U(lin));
	alpha22=sum(gn(lin).*(U(lin).^2));
	D=alpha11*alpha22-alpha12^2;
	sigma_b=sqrt(alpha11/D);
	sigma_a=sqrt(alpha22/D);
    disp('charakteristik, offset,  steigung: ');
    disp([a,sigma_a]);
    disp([b,sigma_b]);


uu = [min(U(lin))*.9:1:max(U(lin))*1.1];

hold on;
plot(uu,a+b*uu);
%plot(U,n1,'. ')
%plot(U,n2,'. ')
%plot(U,n3,'. ')
errorbar(U,n,dn,'.');
hold off;