source ("config/plot-setup.m");
hours = 0:0.5:4;
readings = 2.5.*exp(-0.6.*hours)+0.4 + [0 .02 -.01 .01 -.02 .01 0 -.01 .01];
model = @(theta,t) exp(theta(1)).*exp(-exp(theta(2)).*t)+0.4;
loss = @(theta) sum ((readings-model(theta,hours)).^2);
options = optimset ("Display","off","TolX",1e-10,"TolFun",1e-12,"MaxIter",1000);
[theta,rss,flag] = fminsearch (loss,log([2 .4]),options); assert (flag>0);
fine = linspace (0,4,101);
figure (1); plot (hours,readings,"o",fine,model(theta,fine),"-");
xlabel ("Time (hours)"); ylabel ("Response"); title ("A fitted positive decay model");
grid on; axis padded;
key = legend ("Observed","Fitted model","location","northeast");
set (key,"fontsize",11,"box","off");
printf ("Amplitude: %.6f; decay: %.6f; RSS: %.6f\n", exp(theta(1)),exp(theta(2)),rss);
print (gcf, "figures/OCT-20-006.pdf", "-dpdfcairo");
close all;
