Python matplotlib中的条件函数绘图

Python matplotlib中的条件函数绘图,python,function,matplotlib,plot,conditional,Python,Function,Matplotlib,Plot,Conditional,我的目标是用两个变量t和x绘制一个函数。 如果0,我们将0分配给x import matplotlib.pyplot as plt import numpy as np t=np.linspace(0,5,100) def x(i): if i <= 1: j = 1 else : j = 0 return j y = 8*x(t)-4*x(t/2)-3*x(t*8) plt.plot(t,y) plt.ylabel('y') pl

我的目标是用两个变量t和x绘制一个函数。 如果0,我们将0分配给x
import matplotlib.pyplot as plt
import numpy as np
t=np.linspace(0,5,100)
def x(i):
    if i <= 1:
        j = 1
    else :
        j = 0
    return j
y = 8*x(t)-4*x(t/2)-3*x(t*8)

plt.plot(t,y)
plt.ylabel('y')
plt.xlabel('t')
plt.show()

分配
y
时,您可以循环使用
t
中的值,因为函数
x
只接受一个数字作为其参数。试试这个:

y = np.array([8*x(tt)-4*x(tt/2)-3*x(tt*8) for tt in t])

print y

array([ 1,  1,  1,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,
        4,  4,  4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4,
       -4, -4, -4, -4, -4, -4,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0])

矢量化答案(例如@Christoph和@xnx)是一种更好的方法,尽管在numpy数组上不能使用经典的
if
,至少不能在点方向上使用。这不是问题,因为您可以对数组执行布尔运算:

def x(i):
    j = (i<=1)*1.
    return j
def x(i):

j=(i您的函数
x
无法按原样处理数组输入(由于比较操作)。您可以在此函数中创建一个临时数组,以根据需要设置值:

def x(t):
    tmp = np.zeros_like(t)    
    tmp[t <= 1] = 1
    return tmp
def x(t):
tmp=np.类零(t)

tmp[t你想用这个代码做什么?看看
t
是一个np.array,然后你把它作为一个单一的数字使用,元素操作符在这种情况下不起作用,也许你更喜欢使用一个循环,比如:

import matplotlib.pyplot as plt
import numpy as np
t=np.linspace(0,5,100)
def x(i):
    if i <= 1:
        j = 1
    else :
        j = 0
    return j
y = []
for i in t:
    y.append(8*x(i)-4*x(i/2)-3*x(i*8))

# or using list comprehensions
y = [8*x(i)-4*x(i/2)-3*x(i*8) for i in t]

plt.plot(t,y)
plt.ylabel('y')
plt.xlabel('t')
plt.show()
导入matplotlib.pyplot作为plt
将numpy作为np导入
t=np.linspace(0,5100)
def x(i):
如果我
import matplotlib.pyplot as plt
import numpy as np
t=np.linspace(0,5,100)
def x(i):
    if i <= 1:
        j = 1
    else :
        j = 0
    return j
y = []
for i in t:
    y.append(8*x(i)-4*x(i/2)-3*x(i*8))

# or using list comprehensions
y = [8*x(i)-4*x(i/2)-3*x(i*8) for i in t]

plt.plot(t,y)
plt.ylabel('y')
plt.xlabel('t')
plt.show()