首页 > 解决方案 > 使用 histfit 拟合正态分布时指定 bin 边缘

问题描述

我想使用预定义的 bin 将直方图拟合到某些数据中。我所有的数据点都在 1 到 10 之间,所以我希望这些垃圾箱从 开始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 边缘?

标签: matlabhistogramcurve-fittingnormal-distributionbinning

解决方案


如果您可以访问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)

推荐阅读