%hw3 nlinfit example
%this code creates "experimental data" with error and then fits a model 
%with 2 parameters to this data

global L0; %global parameter, passed into functions with "global L0"

error = 1/100; %amount of experimental noise

L0 = 100.0; %initial concentration of L, in M

t = 0:.01:.11; %time vector

%we will solve for C(t) using the pseudo first-order assumption
%and our initial concentration of receptor (R) is 1M so does not enter the equation
%first, make the true solution (Ctrue) using the true parameters
%then make Cdata, our experimental data (Ctrue+noise)
kon = 1/2; koff = 4; %true parameters
Kd = koff/kon;
Kobs = kon*L0+koff;
for i=1:length(t)
    Ctrue(i) = L0/(L0+Kd).*(1-exp(-Kobs.*t(i))); %R=1
    Cdata(i) = Ctrue(i)+error*(rand-1/2);
end
    
%then, starting with the known initial condition for L
%and guesses for kon and koff, 
%fit the model to the data and get fitted values for kon and koff
k = [0.1, 1.0]; %guesses for kon and koff

%fit 2 parameters: kon and koff
%%%%%%%%%%% the missing line should go below this line %%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%and finally, solve for C using the fitted parameters so you can compare
%the fitted model and the data
kon = fit_k(1) 
koff = fit_k(2)
Kd_fit = koff/kon;
kobs_fit = kon*L0+koff;
for i=1:length(t)     
    Cfitted(i) = L0./(L0+Kd_fit).*(1-exp(-kobs_fit.*t(i))); %R=1
end

figure(1);
plot(t,Ctrue,'b-');
hold on
plot(t,Cdata,'r*');
plot(t,Cfitted,'g-');
legend('true C','C data','fitted solution for C');
xlabel('t');
ylabel('C');
title('solution, using a double fit for kon and koff');
