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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With