Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have two vectors r and d and I'd like to know the number of times r<d(i) where i=1:length(d).

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

So far I've got the following, but it's not very elegant:

for i=1:length(d)
sum(r<d(i))
end

This is an example in R but I'm not really sure this would work for matlab: Finding number of elements in one vector that are less than an element in another vector

like image 984
HCAI Avatar asked Dec 24 '22 02:12

HCAI


2 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);
like image 88
Luis Mendo Avatar answered Jan 17 '23 16:01

Luis Mendo


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);
like image 23
Brice Avatar answered Jan 17 '23 15:01

Brice