Vectorization of loop with find

% 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.

답변 (4개)

Fangjun Jiang
Fangjun Jiang 2011년 10월 8일

0 개 추천

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
Walter Roberson 2011년 10월 8일

0 개 추천

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
Nirmal 2011년 10월 10일

0 개 추천

Great suggestions. Thanks!
Andrei Bobrov
Andrei Bobrov 2011년 10월 10일

0 개 추천

variant
sum(bsxfun(@gt,x(:),0:.1:1))

카테고리

도움말 센터 및 File Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

제품

질문:

2011년 10월 8일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by