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)];
	
	[a,b,da,db,chi2] = linfit(U(lin),n(lin),dn(lin));
	
	
%  	%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,');
    disp([a,da]);
    disp('charakteristik, steigung,');
    disp([b,db]);
    disp('chi2');
    disp(chi2);


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

hold on;
p1=plot(uu,a+b*uu);
p2=errorbar(U,n,dn,'.');
grid on;

ax1=gca;
set(ax1,'YLim',[0,max(n)*1.1]);
set(ax1,'XLim',[min(U)*0.9,max(U)*1.1]);

legend([p2(2),p1],'Gemessen z','linearfit',2);
xlabel('U');
ylabel('z');


hold off;
print -deps2 -tiff -r300 charakter



t=['$U$ & $n1$ & $n2$ & $n3$ & $n$ & $\Delta n$ \\'];
d=latex([U,n1,n2,n3,n,dn],'%3.1f','nomath');
f = fopen('charakter.tab','w');
fwrite(f,d);
fclose(f);
f = fopen('charakter_h.tab','w');
fwrite(f,t);
fclose(f);
