user1594303
user1594303

Reputation: 127

Conditional function plotting in matplotlib

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

Upvotes: 3

Views: 6361

Answers (4)

tmdavison
tmdavison

Reputation: 69126

you could loop over the values in t when assigning y, since your function x only takes one number as its argument. Try this:

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

The vectorised answers (e.g. by @Christoph and @xnx) are a better way to do this, though

Upvotes: 1

efirvida
efirvida

Reputation: 4855

what do you want to do with that code? take a look t is a np.array then you use it as a single number the element wise operator didn’t work in that case maybe you prefer using a loop like:

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

Upvotes: 1

xnx
xnx

Reputation: 25518

Your function x can't handle array inputs as it stands (because of the comparison operations). You could create a temporary array in this function to set the values as appropriate:

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

Upvotes: 3

Christoph
Christoph

Reputation: 1557

You cannot use classical if on numpy arrays, at least not in the pointwise sense. That is not a problem because you can just do boolean operations on the array:

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

Upvotes: 3

Related Questions