Vectorization of loop with find
Show older comments
% I have always wondered how I might be able to vectorize this:
l=0:0.1:1;
a = zeros(length(l),1);
x = rand(1000000,1); % some large array
for i=1:length(l)
a(i) = length(find(x>l(i)));
end
% In the end, basically I just need a count of how many elements of x exceed each value of l
Thank you for your help.
Answers (4)
Fangjun Jiang
on 8 Oct 2011
use hist()
The example below shows how it can be used. The result is the same as a although it is in a slightly different format initially. Note sometimes the numbers may be off by 1. I think it's due to border-line number like 0.1, 0.2, etc. I think you'll get the idea.
x = rand(1000,1); % some large array
b=hist(x);
c=b(end:-1:1);
d=cumsum([0,c]);
l=0:0.1:1;
a = zeros(length(l),1);
for i=1:length(l)
a(i) = length(find(x>l(i)));
end
RevA=a(end:-1:1);
all(d'==RevA)
Walter Roberson
on 8 Oct 2011
Use histc() instead of hist!
a = flipud(cumsum(flipud(histc(x(:), [l*(1+eps),inf], 1))));
The additional argument of 1 to histc fixes the obscure behavior that occurs if x happens to be a scalar.
Nirmal
on 10 Oct 2011
0 votes
Andrei Bobrov
on 10 Oct 2011
variant
sum(bsxfun(@gt,x(:),0:.1:1))
Categories
Find more on Multidimensional Arrays in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!