2

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

1 Answer 1

3

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:

working graph

Sign up to request clarification or add additional context in comments.

1 Comment

This almost worked, but now something very strange is going on. I changed max to np.maximum yet my graph doesn't look like yours, instead it goes through the origin. Any thoughts on why this is? Something weird with my pycharm configurations?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.