MATLAB Answers

Problem Fitting data to 3 Gaussians

3 views (last 30 days)
Jason
Jason on 21 Nov 2016
Commented: Jason on 21 Nov 2016
Hi. I am trying to improve on a gaussian fit to a linescan through the image below.(i.e the green line). Whilst the Gaussian fit isn't too bad, I want to be able to account for the "wings" in the outer parts of the data. This is actually an airy disk.
I thought I could just include another two gaussians in my fitting function to account for these. This is my code:
%Define Gauss Equation (remember the . notation
gaussEqn ='a*exp(-0.5*((x-b)/(c^2)).^2)+d+a1*exp(-0.5*((x-b1)/(c1^2)).^2)+d1+a2*exp(-0.5*((x-b2)/(c2^2)).^2)+d2';
where a,b,c,d are my single gaussian fits and the a1,b1,c1,d1 & a2,b2,c2,d2 are the additional gaussian fits for the outer peaks.
By setting:
a0 = max(ydata(:))-min(ydata(:));
d0 = min(ydata(:));
c=5;
aw=a0/7; (This is the approx amplitude of the "wing" peaks
and the initial parameters as :
[f,gof]=fit(xdata,ydata,gaussEqn,'Normalize','off', 'StartPoint',[a0,b0,sqrt(c0),d0,aw,b0-8,sqrt(c0),d0,aw,b0+8,sqrt(c0),d0])
I am getting silly results, there is something not quite right. The fitting works not too bad for a single exponential, but as soon as i add the other 2 gaussians into the fitting, the results are way off. I have attached the raw data.
a=coeffs(1);
b=coeffs(2);
c=coeffs(3); %need to square it as used c^2 in fitting equation to enforce +ve values
c=c^2;
d=coeffs(4);
rsquared=gof.rsquare;
a1=coeffs(5);
b1=coeffs(6);
c1=coeffs(7);
c1=c1^2;
d1=coeffs(8);
a2=coeffs(9);
b2=coeffs(10);
c2=coeffs(11);
c2=c2^2;
d2=coeffs(12);

  0 Comments

Sign in to comment.

Answers (1)

Massimo Zanetti
Massimo Zanetti on 21 Nov 2016
Edited: Massimo Zanetti on 21 Nov 2016
More efficient using built-in code to fit Guassian distributions. Try look at this function which allows you to choose the number of Gaussian components of the mixture:

  1 Comment

Jason
Jason on 21 Nov 2016
Thanks for the pointer. Its not clear from the examples how I apply this to my line plot (xdata,ydata)?

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!