Julia 中的 MATLAB 历史记录?

MATLAB histcounts in julia?

在MATLAB中,[N,edges,bin] = histcounts(___)可以得到对应元素的bin索引。朱莉娅有没有等效的功能?谢谢!

我已经尝试了 StatsBase.jl 中的直方图和 NaNStatistics.jl 中的 histcounts。似乎 none 个可以得到 bin 索引。

尝试 searchsortedlast 使用直方图的边缘:

julia> dat = rand(20);

julia> h = fit(Histogram, dat, nbins=5)
Histogram{Int64, 1, Tuple{StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}, Int64}}}
edges:
  0.2:0.2:1.0
weights: [8, 4, 3, 5]
closed: left
isdensity: false

julia> searchsortedlast.(Ref(h.edges[1]), dat)'
1×20 adjoint(::Vector{Int64}) with eltype Int64:
 4  3  1  2  4  1  1  2  1  3  1  3  4  2  1  4  4  2  1  1

另一种方法(我觉得更自然)是使用 CategoricalArrays.jl 中的 cut 函数:

using CategoricalArrays
dat = rand(20);
cut(dat, 5)

给你一个分类变量(我不确定在 MATLAB 中什么是等价的)。如果你想要整数级别然后做:

levelcode.(cut(dat, 5))

如果这最终成为来自 Matlab 的人们的常见请求,我 added 向 NaNStatistics 提供一个 histcountindices 函数以响应此 post 应该做你想做的(只需 ] up 即可确保您拥有最新版本)。这应该还是相当快的:

julia> using NaNStatistics, BenchmarkTools

julia> A = 10*rand(1000);

julia> N, bin = histcountindices(A, 0:1:10)
([110, 84, 90, 99, 95, 106, 94, 114, 112, 96], [4, 3, 8, 8, 8, 6, 4, 5, 5, 3  …  6, 2, 9, 5, 2, 9, 10, 2, 7, 3])

julia> @benchmark histcountindices($A, 0:1:10)
BenchmarkTools.Trial: 10000 samples with 7 evaluations.
 Range (min … max):  4.111 μs …  1.156 ms  ┊ GC (min … max):  0.00% … 99.27%
 Time  (median):     4.864 μs              ┊ GC (median):     0.00%
 Time  (mean ± σ):   6.841 μs ± 33.029 μs  ┊ GC (mean ± σ):  14.65% ±  3.13%

    ▁ ▃█
  ▂▄█▅███▄▄▃▃▃▃▂▂▃▃▂▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ ▂
  4.11 μs        Histogram: frequency by time        11.8 μs <

 Memory estimate: 8.17 KiB, allocs estimate: 5.

c.f.

julia> using StatsBase

julia> @benchmark (h = fit(Histogram, $A, 0:1:10); searchsortedlast.(Ref(h.edges[1]), $A))

BenchmarkTools.Trial: 10000 samples with 1 evaluation.
 Range (min … max):  28.723 μs … 996.657 μs  ┊ GC (min … max): 0.00% … 0.00%
 Time  (median):     30.665 μs               ┊ GC (median):    0.00%
 Time  (mean ± σ):   34.875 μs ±  18.328 μs  ┊ GC (mean ± σ):  0.00% ± 0.00%

  ▇█▅▃▅▃▄▂ ▆▃    ▅▂▁▂ ▁ ▄▄                               ▃▁    ▂
  ████████████▇▆▆██████▇███▇▆▇▆▆▅▆▅▅▆█▅▅▅▅▄▄▅▄▄▅▄▄▄▂▄▂▄▅▄██▇▅▅ █
  28.7 μs       Histogram: log(frequency) by time      65.5 μs <

 Memory estimate: 8.14 KiB, allocs estimate: 3.