Sorting items into bins in MATLAB

13,218

Solution 1

The related function histc does this, but it requires you to define the bin edges instead of bin centers.

Y = rand(1, 10);
edges = .1:.1:1;
[N, I] = histc(Y, edges);

Computing the edges given the bincenters is easy too. In a one liner:

N = hist(Y, X);

becomes

[Nc, Ic] = histc(Y, [-inf X(1:end-1) + diff(X)/2, inf]);

with Nc == N, plus one extra empty bin at the end (since I assume no value in Y matches inf). See doc histc.

Solution 2

If one is satisfied with using bin edges instead of bins,

[N,bin] = histc(y,binedges)

works. Aaargh, MATLAB your function definitions are so nonintuitive

Share:
13,218
Marc
Author by

Marc

Updated on June 19, 2022

Comments

  • Marc
    Marc almost 2 years

    If I have a set of data Y and a set of bins centered at X, I can use the HIST command to find how many of each Y are in each bin.

    N = hist(Y,X)
    

    What I would like to know is if there is a built in function that can tell me which bin each Y goes into, so

    [N,I] = histMod(Y,X)
    

    would mean that Y(I == 1) would return all the Y in bin 1, etc.

    I know how to write this function, so I am only wondering if there is already a built-in in MATLAB that does this.

  • Marc
    Marc over 13 years
    Actually, the conversion between bin centers and bin edges is non-trivial if the bin centers are not evenly spaced. MATLABs hist command actually gets this wrong, I think. But yeah, this is good enough. Thanks.
  • alexandre iolov
    alexandre iolov over 5 years
    Currently, Matlab documentation recommends using discretize to obtain Ic in this example.