How to model a time series data with a custom function?
Afficher commentaires plus anciens
I'm trying to fit an ex-gaussian function to a time series of data. I tried to use the fit function of MATLAB. I don't know what I'm doing wrong, I'm not finding the best fitting parameters of my function.
Here is my code and an image of the results (plot on the right).

% Ex-Gaussian model
exGaussian = @(mu,sigma,tau,a0,a1,time) a0 + a1/2 .* exp((1./(2*tau)) .* (2.*mu+(sigma.^2./tau)-(2.*time))).*...
erfc((mu+(sigma.^2./tau)-time)./sqrt(2*sigma));
Fs = 20; %sampling frecuency
t = 0:1/Fs:5; %timestamp in seconds
%Parameters for the example data to fit
mu = 2;
sigma = .1;
tau = 1;
a0 = 1;
a1 = 19;
%Example data
y = exGaussian(mu,sigma,tau,a0,a1,t);
figure(1),clf
subplot(1,2,1)
plot(t, y), grid off
title('Example of data')
% Select the options to fit the model
opts = fitoptions('Method','NonlinearLeastSquares',...
'Lower',[0 0 0 5 10],'Upper',[10 2 10 30 50],...
'Startpoint',[1 0.1 0.1 1 1]);
exGfit = fittype('exGaussian(mu,sigma,tau,a0,a1,t)',...
'coefficients',{'mu','sigma','tau','a0','a1'},...
'independent','t','options',opts);
subplot(1,2,2)
[fitResult, fitStats, fitInfo] = fit(t',y',exGfit);
plot(fitResult,'-r',t,y,'.-b');
1 commentaire
Guassians are difficult to fit -- some of the parameters need to be pretty close to the correct value or else you are very likely to get results that are no-where near correct.
That said, in this case it doesn't even do a great job when given the actual parameters as the starting point :(
% Ex-Gaussian model
exGaussian = @(mu,sigma,tau,a0,a1,time) a0 + a1/2 .* exp((1./(2*tau)) .* (2.*mu+(sigma.^2./tau)-(2.*time))).*...
erfc((mu+(sigma.^2./tau)-time)./sqrt(2*sigma));
Fs = 20; %sampling frecuency
t = 0:1/Fs:5; %timestamp in seconds
%Parameters for the example data to fit
mu = 2;
sigma = .1;
tau = 1;
a0 = 1;
a1 = 19;
%Example data
y = exGaussian(mu,sigma,tau,a0,a1,t);
figure(1),clf
subplot(1,2,1)
plot(t, y), grid off
title('Example of data')
% Select the options to fit the model
opts = fitoptions('Method','NonlinearLeastSquares',...
'Lower',[0 0 0 5 10],'Upper',[10 2 10 30 50],...
'Startpoint',[mu, sigma, tau, a0, a1]);
exGfit = fittype(exGaussian,...
'coefficients',{'mu','sigma','tau','a0','a1'},...
'independent','time','options',opts);
subplot(1,2,2)
[fitResult, fitStats, fitInfo] = fit(t',y',exGfit)
plot(fitResult,'-r',t,y,'.-b');
Réponse acceptée
Plus de réponses (1)
Prateek
le 9 Jan 2023
1 vote
Hi Ana,
A good way to fit ex-Gaussian function is to use the "interpolant" option in the curve fitting toolbox. I was able to obtain a good fit for the data providede by you:

Hope this helps.
Prateek
Catégories
En savoir plus sur Linear and Nonlinear Regression dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


