%exercise 2 solutions
%this code fits for Kd for the equation for y, fractional saturation
%first, with PFOA, then, without

ex2; %load in L0 and y vectors
    
%FIRST WITH PFOA

%first, see what happens when you use your guessed kd and compare to the y data
kd_guess = 1e-2;
%solve for y using your guess
for i=1:length(L0)
    y_wrong(i) = L0(i)/(L0(i)+kd_guess);
end

figure(1);
plot(L0,y,'r*');
hold on
plot(L0,y_wrong,'g-');
legend('y data','fractional saturation from guessed kd');
xlabel('[L]_0');
ylabel('y');
title('fractional saturation data: using the WRONG kd');

%fit for kd
[fit_kd, Res, J] = nlinfit(L0,y,@ex2_function_PFOA,kd_guess);

%and lastly, use your fitted kd to solve for y
for i=1:length(L0)
    y_fit(i) = L0(i)/(L0(i)+fit_kd);
end


figure(2);
plot(L0,y,'r*');
hold on
plot(L0,y_fit,'g-');
legend('y data','y model from fitted Kd');
xlabel('[L]0');
ylabel('y');
title('fitted y compared to data, using PFOA ');

%plot the residuals... Looks like systematic error to me!
figure(3);
plot(L0,Res,'b*');
xlabel('[L]0');
ylabel('residuals');
title('residuals from fit of y to data, using PFOA');


%Hmmm... the PFOA was wrong. Let's try the full equation.
global P0
P0 = 1e-6; %M
[fit2_kd, Res2, J] = nlinfit(L0,y,@ex2_function,kd_guess);

%use your fitted kd to solve for y
for i=1:length(L0)
    y_fit(i) = ((L0(i)+P0+fit2_kd)-(sqrt((L0(i)+P0+fit2_kd)^2-(4*P0*L0(i)))))/(2*P0);
end


figure(4);
plot(L0,y,'r*');
hold on
plot(L0,y_fit,'g-');
legend('y data','y model from fitted Kd');
xlabel('[L]0');
ylabel('y');
title('fitted y compared to data, withOUT using the PFOA ');

%plot the residuals... Now the error looks much more random. Good!
figure(6);
plot(L0,Res2,'b*');
xlabel('[L]0');
ylabel('residuals');
title('residuals from fit of y to data, without using PFOA');
