Search code examples
matlabmode

Matlab: find mode in range


I have a matrix like:

A=
    10 31 32 22
    32 35 52 77
    68 42 84 32

I need a function like mode but with range, for example mymode(A,10) that return 30, find most frequent number in range 0-10, 10-20, 20-30, .... and return most number in range.


Solution

  • You can use histc to bin your data into the ranges of your desire and then find the bin with the most members using max on the output of histc

    ranges = 0:10:50;                 % your desired ranges
    [n, bins] = histc(A(:), ranges);  % bin the data
    [v,i] = max(n);                   % find the bin with most occurrences
    
    [ranges(i) ranges(i+1)]           % edges of the most frequent bin
    

    For your specific example this returns

    ans =
    
        30    40
    

    which matches with your required output, as the most values in A lay between 30 and 40.