我有一个带有频率F的平方信号,我对正方形启动的时间感兴趣。
def time_builder(f, t0=0, tf=300):
"""
Function building the time line in ms between t0 and tf with a frequency f.
f: Hz
t0 and tf: ms
"""
time = [t0] # /! time in ms
i = 1
while time[len(time)-1] < tf:
if t0 + (i/f)*1000 < tf:
time.append(t0 + (i/f)*1000)
else:
break
i += 1
return time
因此,此功能在T0和TF之间循环以创建一个列表,在该列表中,正方形开始的时间。我很确定这不是最好的方法,我想知道如何改进它。
谢谢。
如果我正确解释了这一点,您正在寻找波浪时间的列表,从T0开始,以TF结束。
def time_builder(f, t0=0, tf=300):
"""
Function building the time line in ms between t0 and tf with a frequency f.
f: Hz
t0 and tf: ms
"""
T = 1000 / f # period [ms]
n = int( (tf - t0) / T + 0.5 ) # n integer number of wavefronts, +0.5 added for rounding consistency
return [t0 + i*T for i in range(n)]
使用标准库python为此可能不是最好的方法...特别是考虑到您可能希望以后再做其他事情。
一种替代方法是使用numpy
。这将使您进行以下
from numpy import np
from scipy import signal
t = np.linspace(0, 1, 500, endpoint=False)
s = signal.square(2 * np.pi * 5 * t) # we create a square signal usign scipy
d = np.diff(s) # obtaining the differences, this tell when there is a step.
# In this particular case, 2 means step up -2 step down.
starts = t[np.where(d == 2)] # take the times array t filtered by which
# elements in the differences array d equal to 2