[英]Condition checking when using numpy.piecewise to generate a piecewise periodic plot
I'm trying to generate a piecewise periodic plot using Numpy and matplotlib, like this: 我正在尝试使用Numpy和matplotlib生成分段周期图,如下所示:
import numpy as np
import matplotlib.pyplot as plt
Q1 = lambda t, f, Q_max: Q_max * np.sin(2 * np.pi *f * t)
Q2 = lambda t, f, Q_max: 0
def Q_true(t, f, stat):
while(t >= 1/f):
t -= 1/f
while(t < 0):
t += 1/f
return ((t <= 1/(2*f)) == stat)
Q = lambda t, f, Q_max: np.piecewise(t, [Q_true(t, f, True) , Q_true(t,f, False)], [Q1, Q2], f, Q_max)
Q_max = 225 # mL/sec
f = 1.25 # Hz
t = np.linspace(0,4,101) # secs
plt.plot(t, Q(t, f, Q_max))
The problem is that Q_true
is receiving the entire t
array instead of individual points. 问题是
Q_true
正在接收整个t
数组而不是单个点。 This isn't an issue if I just use less than/greater than statements in the numpy.piecewise
condlist, but it's much easier to determine whether it's true or false using Q_true
. 如果我只使用
numpy.piecewise
condlist中的小于/大于语句,这numpy.piecewise
问题,但使用Q_true
确定它是真还是假更容易。
The plot should look something like this: 情节看起来应该是这样的:
Any ideas? 有任何想法吗?
Thanks! 谢谢!
The following version of Q_true
works: 以下版本的
Q_true
有效:
def Q_true(t, f, stat):
period = 1/f
return (t % period < period/2) == stat
Note that you are naming your anonymous functions ( Q1 = lambda ...
). 请注意,您正在命名匿名函数(
Q1 = lambda ...
)。 In this case you should just define the function using def
. 在这种情况下,您应该使用
def
定义函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.