-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfit_single_exponential.m
More file actions
58 lines (47 loc) · 1.11 KB
/
fit_single_exponential.m
File metadata and controls
58 lines (47 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
function [start,amplitude,rate,r_squared,y_fit]=fit_single_exponential(x,y);
% Fit exponential
% Deduce whether it is building or declining
poly_values=polyfit(x,y,1);
if (poly_values(1)>0)
% Building
build_mode=1;
else
% Declining
build_mode=-1;
end
% Now deduce initial guesses
sorted_y=sort(y);
min_y=min(y);
max_y=max(y);
if (build_mode==1)
guess_half_index=find(sorted_y>(min_y+(0.5*(max_y-min_y))),1,'first');
p(1)=max_y;
p(2)=min_y-max_y;
else
guess_half_index=find(sorted_y<(min_y+(0.5*(max_y-min_y))),1,'last');
p(1)=min_y;
p(2)=max_y-min_y;
end
% Error checking
if (isempty(guess_half_index))
guess_half_index=1;
end
p(3)=-log(0.5)/(x(guess_half_index)-x(1));
options = optimset('TolX',1e-5);
p=fminsearch(@single_exponential_fit,p,options,x,y);
start=p(1);
amplitude=p(2);
rate=p(3);
y_fit=start+amplitude*exp(-abs(rate*(x-x(1))));
r_squared=calculate_r_squared(y,y_fit);
function error = single_exponential_fit(p,x,y)
fit=p(1)+p(2)*exp(-abs(p(3))*(x-x(1)));
error=sum((fit-y).^2);
p(3);
% figure(88)
% clf
% hold on
% plot(fit,'r')
% plot(y,'b')
% pause(0.1)
% drawnow