Count values in a vector less than each one of the elements in another vector

Viewed 100
3 Answers

You can use singleton expansion with bsxfun: faster, more elegant than the loop, but also more memory-intensive:

result = sum(bsxfun(@lt, r(:), d(:).'), 1);

In recent Matlab versions bsxfun can be dropped thanks to implicit singleton expansion:

result = sum(r(:)<d(:).', 1);

An alternative approach is to use the histcounts function with the 'cumcount' option:

result = histcounts(r(:), [-inf; d(:); inf], 'Normalization', 'cumcount');
result = result(1:end-1);

You may build a matrix flagging values from vector r inferior to values from vector d in one time with bsxfun, then sum the values:

flag=bsxfun(@lt,r',d);
result=sum(flag,1);

For each element in d, count how many times this element is bigger than the elements in r, which is equivalent to your problem.

r=rand(1,10);
d=linspace(0,1,10);

result = sum(d>r(:))

Output:

result =
     0     0     1     2     7     8     8     8     9    10
Related