我想知道是否有一种快速方法可以在找到阈值之前对元素进行求和。
例如
threshold=100;
a=0; MAX=1000;
for i=1:MAX
a=a+normrnd(2,1,1,1);
if (a>threshold)
index=i; break;
end
end
这很好用,但速度很慢。 Cumsum在这里真的很有用。但是,我知道在这种情况下使用cumsum的唯一方法是:
a=cumsum(normrnd(2,1, MAX,1));
index=find(a>threshold,1);
当MAX增加时,效率会逐渐降低。
所以基本上我正在寻找一种累积求和方法来保持cumsum的速度,但这允许我设置一个阈值。 任何的想法? 谢谢
答案 0 :(得分:3)
您可以使用二进制搜索。如果您的元素是具有已知分布的随机变量,或者至少已知的预期值,则可以进行良好的初始猜测。
如果您已发布,我们有E[normrnd(2,1,1,1)] = 2
,自threshold = 100
开始,您就会生成50个数字并对其进行求和。如果您高估了,则使用二分搜索搜索正确的索引。如果你低估那么你使用你低估的金额来做出新的猜测,并继续这样做,直到你高估。
答案 1 :(得分:1)
基本上,此解决方案结合了您的解决方案,它遍历大小为1000的细分,并使用您的cumsum解决方案一次处理1000个元素。
threshold=100;
a=0; MAX=9999999;
%segment size
S=1000;
for segment_start=1:S:MAX
%process segment from _start to _end
segment_end=min(segment_start+S-1,MAX);
%which contains _count elements
segment_count=segment_end-segment_start+1;
%now use the cumsum solution to process the segment
c=normrnd(2,1,segment_count,1);
c=cumsum(c);
index=find(c>threshold-a,1,'first');
if isempty(index)
%need to continue
a=a+c(end);
else
%threshhold reached, found solution
a=a+c(index);
break;
end
end