Matplotlib中的条件函数绘图

3

My aim is to plot a function with two variable t and x. we assign 0 to x if 0

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

it return an error :

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

4个回答

3

在numpy数组上,你不能使用传统的if语句,至少不能以逐点的方式。但这并不是问题,因为你可以直接对数组进行布尔运算:

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

3

您的函数 x 不能处理数组输入(因为比较操作)。您可以在此函数中创建临时数组以根据需要设置值:

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

1
当分配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提供的答案)是更好的方法,不过。

1

你想用那段代码做什么?看看 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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接