官方文档中替换不建议使用的 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) |
|