替换不建议使用的 hist 和 histc 实例
旧直方图函数(hist
和 histc
)
MATLAB® 早期版本使用 hist
和 histc
函数作为创建直方图和计算 bin 计数的主要方法。这些函数适用于某些常规用途,但总体能力有限。基于这些原因(及其他原因),不建议在新代码中使用 hist
和 histc
:
使用
hist
创建直方图后,修改该直方图的属性会有难度并要求重新计算整个直方图。hist
的默认行为是使用 10 个 bin,这对很多数据集都不适用。绘制归一化直方图需要手动计算。
hist
和histc
的行为并不一致。
推荐的直方图函数
histogram
、histcounts
和 discretize
函数显著提高了 MATLAB 中创建和计算直方图的能力,同时提升了一致性和易用性。要为新代码创建和计算直方图,推荐使用 histogram
、histcounts
和 discretize
函数。
请特别注意以下更改,它们体现了相对于 hist
和 histc
的改进:
histogram
可以返回一个直方图对象。您可以使用该对象修改直方图的属性。histogram
和histcounts
都具有自动分 bin 和归一化功能,内置了几个常用选项。histcounts
是histogram
的主要计算函数。这样各函数就具有一致的行为。discretize
为确定每个元素的 bin 位置提供了其他选择和灵活性。
要求代码更新的差异
尽管做出了上述改进,但旧函数和当前建议的函数之间存在一些重要差异,这可能需要更新您的代码。下表汇总了这些函数之间的差异并提供了代码更新建议。
hist
的代码更新
差异 | 使用 hist 时的旧行为 | 使用 histogram 时的新行为 |
---|---|---|
输入矩阵 |
A = randn(100,2); hist(A) |
A = randn(100,2); h1 = histogram(A(:,1),10) edges = h1.BinEdges; hold on h2 = histogram(A(:,2),edges) 以上代码示例对每个直方图使用相同的 bin 边界,但在某些情况下,最好将每个直方图的 |
Bin 设定 |
|
要将 bin 中心转换为 bin 边界以用于 注意 若用于 histogram(A,'BinLimits',[-3,3],'BinMethod','integers') |
输出参量 |
A = randn(100,1); [N, Centers] = hist(A) |
A = randn(100,1); h = histogram(A); N = h.Values Edges = h.BinEdges 注意 要计算 bin 计数(而不绘制直方图),请将 |
默认 bin 数量 | 默认情况下, | 默认情况下, A = randn(100,1); histogram(A) histcounts(A) |
bin 范围 |
| 如果未设置 要重新生成 A = randi(5,100,1); histogram(A,10,'BinLimits',[min(A) max(A)]) |
histc
的代码更新
差异 | 使用 histc 时的旧行为 | 使用 histcounts 时的新行为 |
---|---|---|
输入矩阵 |
A = randn(100,10); edges = -4:4; N = histc(A,edges) |
A = randn(100,10); edges = -4:4; N = histcounts(A,edges) 对每列使用 for 循环计算 bin 计数。 A = randn(100,10); nbins = 10; N = zeros(nbins, size(A,2)); for k = 1:size(A,2) N(:,k) = histcounts(A(:,k),nbins); end 如果由于矩阵中的列数很多而造成性能问题,请考虑继续使用 |
最后一个 bin 中包含的值 | 如果 | 如果 A = 1:4; edges = [1 2 2.5 3] N = histcounts(A) N = histcounts(A,edges)
N = histcounts(A,'BinMethod','integers'); |
输出参量 |
A = randn(15,1); edges = -4:4; [N,Bin] = histc(A,edges) |
|
将 bin 中心转换为 bin 边
hist
函数接受 bin 中心,而 histogram
函数接受 bin 边界。要更新代码以使用 histogram
,您可能需要将 bin 中心转换为 bin 边界,以重现使用 hist
实现的结果。
例如,指定 bin 中心以用于 hist
。这些 bin 具有均匀的宽度。
A = [-9 -6 -5 -2 0 1 3 3 4 7]; centers = [-7.5 -2.5 2.5 7.5]; hist(A,centers)
要将 bin 中心转换为 bin 边界,请计算 centers
中各连续值之间的中点。此方法会重现均匀和非均匀 bin 宽度对应的 hist
结果。
d = diff(centers)/2; edges = [centers(1)-d(1), centers(1:end-1)+d, centers(end)+d(end)];
hist
函数包括落入每个 bin 右边界上的值(第一个 bin 包含两个边界),而 histogram
包括落入每个 bin 左边界上的值(最后一个 bin 包含两个边界)。稍微移动 bin 边界以获得与 hist
相同的 bin 计数。
edges(2:end) = edges(2:end)+eps(edges(2:end))
edges = 1×5
-10.0000 -5.0000 0.0000 5.0000 10.0000
现在,将 histogram
与 bin 边界结合使用。
histogram(A,edges)