【发布时间】:2014-07-14 22:52:36
【问题描述】:
我不想找到列表或数组中大于特定threshold 的所有样本/数据点,我只想找到signal 大于threshold 的第一个样本。信号可能会多次跨越阈值。例如,如果我有一个示例信号:
signal = [1, 2, 3, 4, 4, 3, 2, 1, 0, 3, 2, 1, 0, 0, 1, 1, 4, 8, 7, 6, 5, 0]
还有一个threshold = 2,然后
signal = numpy.array(signal)
is_bigger_than_threshold = signal > threshold
会给我signal 中大于threshold 的所有值。
但是,每当信号变得大于阈值时,我只想获得第一个样本。因此,我正在浏览整个列表并进行布尔比较,例如
first_bigger_than_threshold = list()
first_bigger_than_threshold.append(False)
for i in xrange(1, len(is_bigger_than_threshold)):
if(is_bigger_than_threshold[i] == False):
val = False
elif(is_bigger_than_threshold[i]):
if(is_bigger_than_threshold[i - 1] == False):
val = True
elif(is_bigger_than_threshold[i - 1] == True):
val = False
first_bigger_than_threshold.append(val)
这给了我想要的结果,即
[False, False, True, False, False, False, False, False, False, True, False, False, False,
False, False, False, True, False, False, False, False, False]
在 MATLAB 中我也会这样做
for i = 2 : numel(is_bigger_than_threshold)
if(is_bigger_than_threshold(i) == 0)
val = 0;
elseif(is_bigger_than_threshold(i))
if(is_bigger_than_threshold(i - 1) == 0)
val = 1;
elseif(is_bigger_than_threshold(i - 1) == 1)
val = 0;
end
end
first_bigger_than_threshold(i) = val;
end % for
是否有更有效(更快)的方法来执行此计算?
如果我在 Python 中生成数据,例如
signal = [round(random.random() * 10) for i in xrange(0, 1000000)]
然后计时,计算这些值需要4.45 秒。如果我在 MATLAB 中生成数据
signal = round(rand(1, 1000000) * 10);
并执行程序只需0.92 秒。
为什么 MATLAB 执行这项任务的速度几乎是 Python 的 5 倍?
提前感谢您的 cmets!
【问题讨论】:
标签: python matlab numpy threshold