Vectorization of loop with find
Mostra commenti meno recenti
% 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.
Risposte (4)
Fangjun Jiang
il 8 Ott 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
il 8 Ott 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
il 10 Ott 2011
0 voti
Andrei Bobrov
il 10 Ott 2011
variant
sum(bsxfun(@gt,x(:),0:.1:1))
Categorie
Scopri di più su Multidimensional Arrays in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!