Weird unexplainable results when fitting gaussian curve
5 views (last 30 days)
Show older comments
I'm getting bizarre unexplainable results when I fit a Gaussian to a curve. It's all in the code below. Something about using xcorr with the 'biased' parameter causes a Gaussian to be unable to fit. A test example is below.
First, we set up an example of a raster plot which I am using (I'm in the neuroscience field).
nTrials = 100;
x = -3:.05:3;
raster = false(nTrials,length(x));
for ii = 1:nTrials
xVals = randn(1,10);
[~,inds] = min(abs(xVals - x'));
raster(ii,inds) = true;
end
Now, consider two methods I am using to fit a Gaussian to their cross-correlation.
Method 1.
[corrVals,x] = xcorr(raster');
% Remove autocorrelations
identityVals = 1:size(raster,1) + 1:size(corrVals,2);
corrVals(:,identityVals) = nan;
y1 = mean(corrVals,2,'omitnan')';
y1 = y1 / ((length(x) + 1) / 2);
[f,g] = fit(x',y1','gauss1')
Method 2.
[corrVals,x] = xcorr(raster','biased');
% Remove autocorrelations
identityVals = 1:size(raster,1) + 1:size(corrVals,2);
corrVals(:,identityVals) = nan;
y2 = mean(corrVals,2,'omitnan')';
[f,g] = fit(x',y2','gauss1')
y1 and y2 are equal.
plot(x,y1); hold on; plot(x,y2,'ro');
Yet the R2 value (see the field g, generated by the call to fit) is vastly different. In one case, rsquare is .999, and in the other, it's 0.
Please provide insight.
2 Comments
Catalytic
on 17 Mar 2024
Yet the R2 value (see the field g, generated by the call to fit) is vastly different. In one case, rsquare is .999, and in the other, it's 0.
That's not what the code output that you've posted shows. It shows R2=0.6052 in both cases.
Accepted Answer
More Answers (1)
Catalytic
on 18 Mar 2024
Supply a better initial guess than what fit() defaults to -
load data
a0=max(y2) %initial a
b0=x(find(y2==max(y2),1)) %initial b
c0 = sqrt( 2 * y2/sum(y2)*(x(:)-b0).^2 ) %initial c
[f,g]=fit(x',y2','gauss1',StartPoint=[a0,b0,c0])
0 Comments
See Also
Categories
Find more on Interpolation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!