如何在matplotlib上绘制以下函数:
对于[n,n+1]中的所有区间t,n偶数的f(t)=1和n奇数的f(t)=-1。这基本上是一个step函数,f(t)=1从0到1,f(t)=-1从1到2,f(t)=1从2到3,f(t)=-1从3到4,等等。
到目前为止,这是我的代码:
t = arange(0,12)
def f(t):
if t%2 == 0:
for t in range(t,t+1):
f = 1
if t%2 != 0:
for t in range(t,t+1):
f = -1这是这个代码的过程:
f(t)。t=0,2,4,6,8,10,12。f=1。您能看到这段代码有什么根本问题吗?我让事情变得复杂了吗?
当我试图用
matplotlib.pyplot.plot(t,f,'b-')
matplotlib.pyplot.show()我得到一个ValueError,上面写着"x和y必须有相同的第一维“。
这里出什么问题了?
发布于 2015-12-02 10:08:31
可以使用numpy.repeat将数组t中的元素加倍,并使用1 - 2 * (t%2)构建(-1,1)模式
t = np.arange(13)
f = np.repeat(1 - 2 * (t%2), 2)[:-1]
t = np.repeat(t, 2)[1:]
In [6]: t
Out[6]:
array([ 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
9, 9, 10, 10, 11, 11, 12, 12])
In [7]: f
Out[7]:
array([ 1, 1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1,
1, -1, -1, 1, 1, -1, -1, 1])也许更容易的是:
In [8]: n = 12
In [9]: t = np.repeat(np.arange(n+1), 2)[1:-1]
In [10]: f = np.array([1,1,-1,-1]*(n//2))https://stackoverflow.com/questions/34038629
复制相似问题