简体   繁体   English

如何使用matplotlib绘制此步进函数?

[英]How can I plot this step function using matplotlib?

How can I plot the following function on matplotlib: 如何在matplotlib上绘制以下函数:

For all intervals t in [n,n+1] , f(t)=1 for n even and f(t)=-1 for n odd. 对于所有的间隔吨[n,n+1] f(t)=1对于n偶数和f(t)=-1 n为奇数。 So this is basically a step function with f(t)=1 from 0 to 1, f(t)=-1 from 1 to 2, f(t)=1 from 2 to 3, f(t)=-1 from 3 to 4, and so on. 所以这基本上是一个阶跃函数, f(t)=1从0到1, f(t)=-1从1到2, f(t)=1从2到3, f(t)=-1从3至4,依此类推。

This is my code so far: 到目前为止,这是我的代码:

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

This is the process of this code: 这是这段代码的过程:

  1. Define t to be in the range 0 to 12. 将t定义在0到12的范围内。
  2. Define the function f(t) . 定义函数f(t)
  3. Use the statement, if t is an even integer, so it will consider t=0,2,4,6,8,10,12 . 如果t是偶数整数,请使用该语句,因此它将考虑t=0,2,4,6,8,10,12
  4. Use the for loop to allow us to define f=1 for each of these integers. 使用for循环可让我们为这些整数中的每一个定义f=1
  5. Repeat for odd values of t. 重复输入t的奇数。

Can you see anything fundamentally wrong with this code? 您能看到此代码有什么根本错误的地方吗? Am I complicating things? 我在使事情复杂化吗?

When I try to plot using 当我尝试使用

matplotlib.pyplot.plot(t,f,'b-')
matplotlib.pyplot.show()

I get a ValueError saying "x and y must have same first dimension". 我收到一个ValueError说“ x和y必须具有相同的第一维”。

What is going wrong here? 这是怎么了?

You could use numpy.repeat to double up elements in your array t , and build the (-1,1) pattern with 1 - 2 * (t%2) : 您可以使用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])

Perhaps even easier is: 也许更容易的是:

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM