Question

Consider this :

a = [1 ; 7 ; 13];
edges = [1, 3, 6, 9, 12, 15];

[~, bins] = histc(a, edges)

bins =

     1
     3
     5

Now I would like to have the same output, but with a different "edges" vector for each a value, i.e. a matrix instead of a vector for edges. Exemple :

   a = [1 ; 7 ; 13];
    edges = [ 1, 3, 6 ; 1, 4, 15 ; 1, 20, 30];

edges =

     1     3     6
     1     4    15
     1    20    30


    indexes = theFunctionINeed(a, edges);

    indexes = 
            1   % 1 inside [1, 3, 6]
            2   % 7 indide [1, 4, 15]
            1   %13 inside [1, 20, 30]

I could do this with histc inside a for loop, by I'm trying to avoid loops.

Was it helpful?

Solution

If you transform your arrays to cell arrays, you can try

a = {1 ; 7 ; 13};
edges = {[ 1, 3, 6 ];[ 1, 4, 15] ; [1, 20, 30]};

[~, indexes] = cellfun(@histc, a, edges,'uniformoutput', false)

This results in

indexes = 

    [1]
    [2]
    [1]

~edit~

To transform your matrices into cell arrays you can use num2cell:

a  = num2cell(a); 
edges = num2cell(edges, 2);

OTHER TIPS

You could also do:

a = [1; 7; 13];
edges = [1 3 6; 1 4 15; 1 20 30];

bins = sum(bsxfun(@ge, a, edges), 2)

The result:

>> bins
bins =
     1
     2
     1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top