Reputation: 21
I'm trying to plot two functions func1 and func2 using matplotlib and python. I keep getting a ValueError for the following code and have no idea what is wrong. I've searched through related questions, tried a ton of things, and nothing seems to work.
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)
plt.xlim(0, 10)
plt.ylim(0, 10)
plt.xlabel('$X$')
plt.ylabel('$Outputs$')
plt.title('Title')
x = np.arange(0, 10, .1)
def func1(X):
output = max(3*X/7 - 3/7, 0, 12*X/35 - 3/35)
return output
def func2(X):
output = max(3*X/7 - 3/7, 0)
return output
plt.plot(x, func1(x), 'g')
plt.plot(x , func2(x), 'b')
plt.show()
Upvotes: 2
Views: 7824
Reputation: 353059
max(2,3)
is clearly 3, because 3 > 2
.
But when we compare ndarray arguments, we don't get a single scalar result, but an array:
In [23]: np.array([3,1]) > np.array([1,2])
Out[23]: array([ True, False], dtype=bool)
and we can't convert an array of bools into a single value-- should it be True, because there's at least one, or False, because it's not all True? Or, as the error message puts it, "The truth value of an array with more than one element is ambiguous". This means that the builtin max
function fails, because it tries to branch on whether a comparison is true or not.
Fortunately, as it looks like you want the pairwise maxima, numpy already has a function which handles that, np.maximum
. Replacing the builtin max
with np.maximum
in your code gives me:
Upvotes: 3