Curve fitting toolbox giving different answer to custom function?

1 view (last 30 days)
Hello,
I have data which looks like this when plotted:
A custom equation summing a linear slope and a Gaussian gives me a really nice fit:
However, when I try to implement that as code, the fit fails pretty spectacularly.
% energy = 100-by-1 double
% counts = 100-by-1 double (both cropped from main data)
% if I use the toolbox to fit using 'energy' as the x-axis, it fails. However, if I use xdat it gives the result shown above.
xdat = linspace(1,length(counts), length(counts))';
% All this I copied from the 'Generate Code' option under 'File'. I thought I had a problem with StartPoint, but they're
[xData, yData] = prepareCurveData( xdat, counts );
% Set up fittype and options.
ft = fittype( '(m*x+c) + a1*exp(-((x-b1)/c1)^2)', 'independent', 'x', 'dependent', 'y' );
opts = fitoptions( 'Method', 'NonlinearLeastSquares' );
opts.Display = 'Off';
opts.StartPoint = [0.3302 0.2297 0.1139 0.3109 0.2284]; % these change, which I didn't expect when fitting the same data.
% Fit model to data.
[fitresult, gof] = fit( xData, yData, ft, opts );
plot(fitresult)
fitresult =
General model:
fitresult(x) = (m*x+c) + a1*exp(-((x-b1)/c1)^2)
Coefficients (with 95% confidence bounds):
a1 = 1042 (1024, 1059)
b1 = 59.75 (59.66, 59.85)
c = 311.4 (302.8, 319.9)
c1 = -7.268 (-7.415, -7.121)
m = -0.9449 (-1.094, -0.7957)
Any clue to where I am failing would be very much appreciated.

Answers (2)

the cyclist
the cyclist on 25 Sep 2019
Edited: the cyclist on 25 Sep 2019
I don't fully understand what is going on here, but if I plot that function over the range 0:100 instead of 0:1, the shape of the curve is replicated:
x = 0 : 1 : 100;
a1 = 1042;
b1 = 59.75;
c = 311.4;
c1 = -7.268;
m = -0.9449;
fitresult = (m*x+c) + a1*exp(-((x-b1)/c1).^2);
figure
plot(x,fitresult)
That makes sense to me, since the exponential term clear has a peak where x == b1. I don't think the data you plotted in your first graph (which peaks around 1.05) is really what was fitted.
  1 Comment
AlexAS
AlexAS on 26 Sep 2019
Thanks for this. I get the same result using your starting points, but it's still not clear to me where I'm going astray. However, I can at least move forward while I figure it out! Cheers, Alex

Sign in to comment.


Alex Sha
Alex Sha on 28 Sep 2019
Hi, AlexAS, I get the global solution as fellow:
Root of Mean Square Error (RMSE): 23.9947153172582
Sum of Squared Residual: 58150.3826787827
Correlation Coef. (R): 0.996437682897764
R-Square: 0.992888055898666
Adjusted R-Square: 0.992742914182312
Determination Coef. (DC): 0.992888055898665
Chi-Square: 98.7754060511867
F-Statistic: 3350.60470214536
Parameter Best Estimate
---------- -------------
a1 1038.49566359074
b1 1.0436517640913
c 387.185685520493
c1 0.036134594114558
m -122.65365053643
c208.jpg

Community Treasure Hunt

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

Start Hunting!