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