问题描述
我想使用预定义的 bin 为某些数据拟合直方图。我的所有数据点都在 1 到 10 之间,因此我希望 bin 从 xmin=1
开始,到 xmax=10
结束,步长为 0.5
。
我使用以下命令:
x = d1.data(:,4); % x is my data
H = histfit(x,10,'normal'); % fits a histogram using 10 bins
但是,在执行上述操作时,每个数据集都会自动确定 bin,并且与我想要的边缘不对应。如何确保所有数据集都使用相同的 bin 边缘?
解决方法
如果您可以访问 Curve Fitting Toolbox,我会建议另一种提供所需灵活性的方法。这涉及“自己”做合适的事情,而不是依赖histfit
:
% Generate some data:
rng(66221105) % set random seed,for reproducibility
REAL_SIG = 1.95;
REAL_MU = 5.5;
X = randn(200,1)*REAL_SIG + REAL_MU;
% Define the bin edges you want
EDGES = 1:0.5:10;
% Bin the data according to the predefined edges:
Y = histcounts(X,EDGES);
% Fit a normal distribution using the curve fitting tool:
binCenters = conv(EDGES,[0.5,0.5],'valid'); % moving average
[xData,yData] = prepareCurveData( binCenters,Y );
ft = fittype( 'gauss1' );
fitresult = fit( xData,yData,ft );
disp(fitresult); % optional
% Plot fit with data (optional)
figure();
histogram(X,EDGES); hold on; grid on;
plot(fitresult);
产生以下图:
和拟合模型:
General model Gauss1:
fitresult(x) = a1*exp(-((x-b1)/c1)^2)
Coefficients (with 95% confidence bounds):
a1 = 19.65 (17.62,21.68)
b1 = 5.15 (4.899,5.401)
c1 = 2.971 (2.595,3.348)