我正在使用下面的python代码,以便为简单的正弦波输入生成反向间隙信号。生成的输出不符合要求。输出应类似于Simulink中使用的反向间隙。
#Importing libraries
import matplotlib.pyplot as plt
import numpy as np
#Setting upper limit and lower limit
LL = -0.5
UL = 0.5
#Generating the sine wave
x=np.linspace(0,10,1000)
y=(np.sin(x))
#phase shift of y1 by -pi/2
y1=(np.sin(x-1.571))
# plot original sine
plt.plot(x,y)
#setting the thresholds
y1[(y1>UL)] = UL
y1[(y1<LL)] = LL
#Initializing at the input
y1[(y==0)] = 0
y1[(y1>UL)] -= UL
y1[(y1<LL)] -= LL
#Plotting both the waves
plt.plot(x,y)
plt.plot(x,y1)
plt.grid()
plt.show()
我不认为对于强拆过程有一个简单的矢量化实现。第k个输出以非平凡的方式取决于先前的值。编写过程的简明方法(假设x
是输入数组,y
是输出数组)是
y[k] = min(max(y[k-1], x[k] - h), x[k] + h)
其中h
是死亡的一半。
以下脚本包含使用Python for循环的backlash
函数。 (该函数使用if
语句而不是min
和max
函数。)它很简单,但速度不会很快。如果高性能很重要,您可以考虑重新实现Cython或numba中的函数。
import numpy as np
def backlash(x, deadband=1.0, initial=0.0):
"""
Backlash process.
This function emulates the Backlash block of Simulink
(https://www.mathworks.com/help/simulink/slref/backlash.html).
x must be a one-dimensional numpy array (or array-like).
deadband must be a nonnegative scalar.
initial must be a scalar.
"""
halfband = 0.5*deadband
y = np.empty_like(x, dtype=np.float64)
current_y = initial
for k in range(len(x)):
current_x = x[k]
xminus = current_x - halfband
if xminus > current_y:
current_y = xminus
else:
xplus = current_x + halfband
if xplus < current_y:
current_y = xplus
y[k] = current_y
return y
if __name__ == "__main__":
import matplotlib.pyplot as plt
t = np.linspace(0, 10, 500)
x = np.sin(t)
deadband = 1
y = backlash(x, deadband=deadband)
plt.plot(t, x, label='x(t)')
plt.plot(t, y, '--', label='backlash(x(t))')
plt.xlabel('t')
plt.legend(framealpha=1, shadow=True)
plt.grid(alpha=0.5)
plt.show()