我正在使用以下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()
答案 0 :(得分:1)
我认为反冲过程没有简单的矢量化实现。第k个输出以非平凡的方式取决于先前的值。编写过程的简洁方法(假设x
是输入数组,y
是输出数组)
y[k] = min(max(y[k-1], x[k] - h), x[k] + h)
其中h
是死区的一半。
以下脚本包括一个backlash
函数,该函数使用Python for循环。 (该函数使用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()