使用 histfit 拟合正态分布时指定 bin 边缘
Specifying bin edges when fitting a normal distribution using histfit
我想使用预定义的 bin 将直方图拟合到某些数据。我所有的数据点都在 1 到 10 之间,所以我希望 bins 从 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)
我想使用预定义的 bin 将直方图拟合到某些数据。我所有的数据点都在 1 到 10 之间,所以我希望 bins 从 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)