Date: Jan 10, 2013 9:17 AM
Subject: Re: Fitting to a Gaussian using nlinfit
"Ben" wrote in message <firstname.lastname@example.org>...
> I have the number concentration per particle size for a range of sizes and for 24 instrument channels. The plot seems to follow a normal distribution and I would like to fit the data to one. My data is not in the form of a probability density function since the y-axis is not probability, but rather concentration. Thus the equation I would like to fit to is: y = H.*exp(-.5.*((dp-mu)/sigma)^2), where H is the height of the distribution.
> Following the methods outlined from the "Curve Fitting and Distribution Fitting" tutorial (http://www.mathworks.com/products/statistics/examples.html?file=/products/demos/shipping/stats/cfitdfitdemo.html), I attempted to use nlinfit to determine the optimal parameters H, mu, sigma. The result is not a good fit, however. I'm getting some errors when I run the code, namely, "Warning: Rank deficient, rank = 2, tol = 5.617004e-06." This, along with the terrible fit, makes me think I'm using this incorrectly.
> Does anyone know what's going on here?
> Here is my code:
> N_data = [
> dp_data = [
> %interpolate between points to get initial guess for height of dist.
> dp_space = logspace(log10(dp_star_meas(1)*0.75),log10(dp_star_meas(length(dp_star_meas))*1.25),1000);
> N_data_intr = interp1(dp_data,N_data,dp_space,'spline',0);
> initial_guesses(1) = peak(N_data_intr);
> %calculate mean and std for initial guess values
> for i = 1:length(N_data)
> mu = mu + dp_space(i)*N_data_intr(i);
> N_tot = N_tot + N_data_intr(i);
> mu = mu/N_tot;
> for i = n:m
> f = f + N_data_intr(i)*(dp_space(i) - mu)^2;
> std = sqrt(f/(N_tot));
> init_guesses(2) = mu;
> init_guesses(3) = std;
> %define function for nlinfit
> norm_func = @(p,dp) p(1).*exp(-.5.*((dp-p(2))/p(3)).^2);
> [bestfit,resid]=nlinfit(dp_data,log(N_data),@(p,x) log(norm_func(p,x)),init_guesses);
> here is an image of the final fit versus the data: http://s2.postimage.org/xeu65jqyx/nlinfit_graph.png
> I appreciate the help
You fit the log of your data against the log of your fit function.
This introduces a distortion to the estimates of your parameters.
Why don't you try the direct way