35 lines
1.1 KiB
Matlab
35 lines
1.1 KiB
Matlab
function [tau, taus, mses] = expdecaydescent(t, x, tau0, epsilon, threshold)
|
|
% Gradient descent for fitting a decaying exponential.
|
|
%
|
|
% Arguments: t, vector of time points.
|
|
% x, vector of the corresponding measured data values.
|
|
% tau0, initial value for the time constant.
|
|
% epsilon: factor multiplying the gradient.
|
|
% threshold: minimum value for gradient
|
|
%
|
|
% Returns: tau, the final value of the time constant.
|
|
% taus: vector with all the tau-values traversed.
|
|
% mses: vector with the corresponding mean squared errors
|
|
tau = tau0;
|
|
gradient = 1000.0;
|
|
taus = [];
|
|
mses = [];
|
|
count = 1;
|
|
while abs(gradient) > threshold
|
|
taus(count) = tau;
|
|
mses(count) = expdecaymse(t, x, tau);
|
|
gradient = expdecaygradient(t, x, tau);
|
|
tau = tau - epsilon * gradient;
|
|
count = count + 1;
|
|
end
|
|
end
|
|
|
|
function mse = expdecaymse(t, x, tau)
|
|
mse = mean((x - expdecay(t, tau)).^2);
|
|
end
|
|
|
|
function gradient = expdecaygradient(t, x, tau)
|
|
h = 1e-7; % stepsize for derivative
|
|
gradient = (expdecaymse(t, x, tau+h) - expdecaymse(t, x, tau))/h;
|
|
end
|