MATLAB histcounts in julia?

Viewed 178

In MATLAB, [N,edges,bin] = histcounts(___) can get bin indices for the corresponding elements. Is there any equivalent function in julia? Thanks!

I already tried Histogram in StatsBase.jl and histcounts in NaNStatistics.jl. It seems none of them can get bin indices.

3 Answers

Try searchsortedlast using edges of the histogram:

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

An alternative way (that I find a bit more natural) it to use the cut function from CategoricalArrays.jl:

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

gives you a categorical variable (I am not sure what would be the equivalent in MATLAB). If you want to have integer level then do:

levelcode.(cut(dat, 5))

In case this ends up being a common request for folks coming from Matlab, I added a histcountindices function to NaNStatistics in response to this post which should do what you want (just ] up to make sure you have the latest version). This should still be quite fast:

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.
Related