
% Define the data sets that you are trying to fit the
% function to.  Make sure to import these into MatLab before running this
t = (Pt_data1(:,1) + Pt_data1(:,2))/2;
r = Pt_data1(:,6);
offsetfix = 1.480;
%offsetfix
% Initialize the coefficients of the function
X0=[90000 230 1.5];

 
% Set an options file for LSQNONLIN to use the
% medium-scale algorithm
options = optimset('Largescale','off');
 
% Calculate the new coefficients using LSQNONLIN
[params,renorm]=lsqnonlin(@fit_simp_Pta,X0,[],[],options,t,r, offsetfix);
 
%define the fitted function
z=params(2)./t;
J51=120*zeta(5)-exp(-1.0.*z).*(z.^5+5*z.^4+20*z.^3+60*z.^2+120.*z+120);
J52=-exp(-2.0.*z).*(z.^5+5*z.^4/2+20*z.^3/4+60*z.^2/8+120.*z/16+120/32);
J53=-exp(-3.0.*z).*(z.^5+5*z.^4/3+20*z.^3/9+60*z.^2/27+120.*z/81+120/243);
J54=-exp(-4.0.*z).*(z.^5+5*z.^4/4+20*z.^3/16+60*z.^2/64+120.*z/256+120/1024);
J55=-exp(-5.0.*z).*(z.^5+5*z.^4/5+20*z.^3/25+60*z.^2/125+120.*z/625+120/3125);
J56=-exp(-6.0.*z).*(z.^5+5*z.^4/6+20*z.^3/36+60*z.^2/216+120.*z/1296+120/7776);
J57=-exp(-7.0.*z).*(z.^5+5*z.^4/7+20*z.^3/49+60*z.^2/343+120.*z/2401+120/16807);
J58=-exp(-8.0.*z).*(z.^5+5*z.^4/8+20*z.^3/64+60*z.^2/512+120.*z/4096+120/32768);
J59=-exp(-9.0.*z).*(z.^5+5*z.^4/9+20*z.^3/81+60*z.^2/729+120.*z/6561+120/59049);
J510=-exp(-10.0.*z).*(z.^5+5*z.^4/10+20*z.^3/100+60*z.^2/1000+120.*z/10000+120/100000);
BG1=t.^5/(params(2))^6.*J51;
BG2=t.^5/(params(2))^6.*J52;
BG3=t.^5/(params(2))^6.*J53;
BG4=t.^5/(params(2))^6.*J54;
BG5=t.^5/(params(2))^6.*J55;
BG6=t.^5/(params(2))^6.*J56;
BG7=t.^5/(params(2))^6.*J57;
BG8=t.^5/(params(2))^6.*J58;
BG9=t.^5/(params(2))^6.*J59;
BG10=t.^5/(params(2))^6.*J510;
BGT=BG1+BG2+BG3+BG4+BG5+BG6+BG7+BG8+BG9+BG10;
Y_fit =	offsetfix+params(1)*(BGT);
%plot the data along with the fit function
%plot(t,Y_fit,'r')

y = (Y_fit - Pt_data1(:,6));
ylength = length(y);
for i = 1:ylength
    y(i) = y(i)^2;
end
ysum = sum(y);
chi2 = ysum/(ylength-1);
%params
%chi2
%r_zero = 1.48;
n = 0;
%y
for i = 1:length(t)
    if t(i) > 213
        n = i; 
        break;
    end
end

r_0 = 1.48;    
r_debye = r(n);
t_debye = 213;
r_reduced = (r - r_0)/(r_debye - r_0);
t_reduced = t/t_debye;
%t_reduced
%plot(t_reduced,r_reduced,'b');
hold;

t_reduced;
for i = 1:length(r_reduced)
    %you forgot to compare temperature
    if t_reduced(i) < 40/t_debye
        tlow(i) = t_reduced(i);
        rlow(i) = r_reduced(i);
        %tlow(i)
        n = i;
        %40/t_debye  
    end
    
    %tlow(i)
end
%tlow
%length(tlow)
%n = n+1;

for i = n: length(r_reduced)
    thigh(1 + i-n) = t_reduced(i);
    %t_reduced(i)
    rhigh(1 + i-n) = r_reduced(i);
end

%tlow
%thigh
%length(thigh)
%length(t_reduced)
%[b, errorlow] = lsqcurvefit(@quintFun, 1, tlow, rlow);
%[a, errorhigh] = lsqcurvefit(@linFun, 1, thigh, rhigh);
%tlow
%c=497.6;
%plot(tlow, c*tlow.^5, 'r');
%b
%a