Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Topic: Fitting to a Gaussian using nlinfit
Replies: 5   Last Post: May 23, 2013 1:10 PM

 Messages: [ Previous | Next ]
 Tom Lane Posts: 858 Registered: 12/7/04
Re: Fitting to a Gaussian using nlinfit
Posted: Jan 10, 2013 10:52 AM

Ben, nlinfit is doing a couple of things that are difficult in your problem.
First, it is trying to compute derivatives numerically by perturbing the
parameters a bit. Second, it is trying to measure convergence using the
change in parameters from one iteration to another. This is hard because you
have one parameter of the order of 1e12, and others of the order of 1e-8. A
simple way to avoid the problem is to build these scale factors into your
model, and make sure the parameters being estimated are of comparable
magnitude. The following shows how to do this on either the original or log
scale.

subplot(2,1,1)
init_guesses = [1 3 1];
norm_func = @(p,dp) 2e12*p(1).*exp(-.5.*((dp-1e-8*p(2))/(p(3)*1e-8)).^2);
[bestfit,resid]=nlinfit(dp_data,log(N_data),@(p,x)
log(norm_func(p,x)),init_guesses);
xx = linspace(min(dp_data),max(dp_data));
plot(dp_data, log(N_data),'bo', xx,log(norm_func(bestfit,xx)),'r-',
xx,log(norm_func(init_guesses,xx)),'g-')

subplot(2,1,2)
[bestfit,resid]=nlinfit(dp_data,N_data,@(p,x) norm_func(p,x),init_guesses);
plot(dp_data, N_data,'bo', xx,norm_func(bestfit,xx),'r-',
xx,norm_func(init_guesses,xx),'g-')

Further hint: when you post code, make sure it runs. You had multiple
undefined variables in your code. That's why I supplied my own init_guesses,
bypassing that part of your code.

-- Tom

Date Subject Author
1/10/13 Torsten
1/10/13 Torsten
1/10/13 Tom Lane
5/23/13 Nathan Orloff