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
2011-10-8
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
2011-10-8
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.
Andrei Bobrov
2011-10-10
variant
sum(bsxfun(@gt,x(:),0:.1:1))
类别
在 帮助中心 和 File Exchange 中查找有关 Multidimensional Arrays 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!