我在matlab中创建了一个很难用函数来描述的timeseries数据,我想知道如何将它移植到Python中。问题是python中的计时器很少(如果有的话)接受数据集的精确值。我很确定这样的方法会奏效:
#this is matlab code just to represent the data
t=linspace(t0,tf,samples);
dataseries;
input=timeseries(dataseries,t);
#python code
def f(timer):
for i in range(0,len(t)):
if timer>t[i] and timer<=t[i+1]:
f=dataseries[i]
else:
pass
output=f(timer)
但我觉得这会非常慢,因为每次代码块运行时都要检查所有的t。有没有更简单的方法来获得这个功能?以下内容可能会快一点,但看起来仍然很脏:
def f(timer):
for i in range(0,len(t)):
diff[i]=np.abs(timer-t[i])
location=np.argmin(diff)
f=dataseries[location]
output=f(timer)
我知道我可以用傅里叶级数来近似函数,但在这种情况下,精度很重要,所以我更希望输出尽可能精确。Python中是否有用于此的内置函数?你知道吗
谢谢你的帮助!你知道吗
编辑 这里所要求的是完整的代码,而不仅仅是伪代码。使用此代码可以工作,但正如所预测的那样,它相当慢。我的时间序列是10274点长。每个函数调用需要0.015秒。你知道吗
import scipy
from matplotlib import pyplot as plt
import datetime
import numpy as np
from time import sleep
A=scipy.io.loadmat('data_for_python.mat')
time_series=A['t'][0]
unshaped_in=A['in'][0]
shaped_in=A['real_in'][0]
time0=datetime.datetime.now()
diff=np.ones(len(time_series))*50
print len(time_series)
def f(time):
for i in range(0,len(time_series)):
diff[i]=np.abs(timer-time_series[i])
location=np.argmin(diff)
f=shaped_in[location]
return f
timer=0
while(timer<15):
timer=datetime.datetime.now()-time0
timer=timer.total_seconds()
t0=datetime.datetime.now()
output=f(timer)
t1=datetime.datetime.now()-t0
print 'time:', timer
print 'dt',t1.total_seconds()
print 'output:', output
我建议看一下python的
bisect
模块……有几种方法可以做到这一点,这取决于您是否/如何处理完全相同的情况。bisect_left()
方法返回指定值的数组“右边”的索引,假设时间序列数组是严格排序的。你知道吗如您所见,这通常会为值x提供右端点,除非相等。还有其他不同的方法来处理端点,
bisect()
和bisect_right()
,因此如果您对这种行为感兴趣,我建议您阅读python文档。你知道吗如果要使用左侧索引,只需从返回值中减去一个,如果需要,可以使用该索引将其索引到另一个数组中。但在使用之前,您需要对结果进行错误检查:
相关问题 更多 >
编程相关推荐