Weird unexplainable results when fitting gaussian curve
6 次查看(过去 30 天)
显示 更早的评论
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 个评论
Catalytic
2024-3-17
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.
采纳的回答
更多回答(1 个)
Catalytic
2024-3-18
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Interpolation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!