Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 756
user1594303 Avatar asked Mar 26 '26 04:03

user1594303


1 Answers

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
like image 72
Christoph Avatar answered Mar 28 '26 18:03

Christoph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!