Creating Step Function With Error: The Truth Value Of An Array With More Than One Element Is Ambiguous
I am trying to make a box or step function using if/else statements. For example: import matplotlib.pyplot as plt import numpy as np def V(x): if -1<=x<=1: retur
Solution 1:
Use map
to apply your function to each value of x
:
x = np.linspace(0, 100)
plt.plot(x, list(map(V, x)))
The reason for your error is you are attempting to apply a function on an entire array, when it is designed to work on a single element.
However, a better idea is to vectorise your function:
def V(x):
res = np.zeros(len(x))
res[np.where(np.abs(x)<1)] = 20
return res
x = np.linspace(0, 100)
plt.plot(x, V(x))
Solution 2:
Just loop through x, apply V(x) to each value, and save each value in an array.
y = np.zeros(len(x))
for i,j inenumerate(x):
y[i] = v(j)
plt.plot(x,y)
Post a Comment for "Creating Step Function With Error: The Truth Value Of An Array With More Than One Element Is Ambiguous"