2

Suppose x runs from (0 to 10); now for x<=5, I need to plot 8*x and else I need to plot 50*x. My attempt:

import matplotlib.pyplot as plt
import numpy as np

def f(x):   
    if x<=3:
        return (8*x)
    else:
        return (50*x)


t=np.linspace(0,10,100)

plt.plot(t,f(t))

plt.ylabel('s')
plt.xlabel('t')
plt.show()

But it is showing error:

The truth value of an array with more than one element is ambiguous.

0

3 Answers 3

2

x is an np.array with length 100. Numpy cannot evaluate the truth value of the whole array at once, either one element or all of them.

You have to pass single elements to the function for your comparison to work.


Edit:

either you use a comprehension to pass single elements (or a for loop):

f_t = np.array([f(x) for x in t])
plt.plot(t, f_t)

or a map:

f_t = np.array(list(map(f, t)))
plt.plot(t, f_t)

but according to this article, the comprehension is actually slightly faster than the map...

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

1 Comment

How to pass single elements to the function ?
1

I believe you are asking for an element-wise operation. Here x in a linear array, and you want to perform 8*x(i) if the i'th index of x is less than or equal to 5. Otherwise, you want to perform 50*x(i). Assuming so my solution would be,

import matplotlib.pyplot as plt
import numpy as np

def f(x):
    if x <= 5:
        return 8*x
    else:
        return 50*x


t=np.linspace(0,10,100)
plt.plot(t, np.array(list(map(f, t))))
plt.ylabel('s')
plt.xlabel('t')
plt.show()

The error you received The truth value of an array with more than one element is ambiguous. indicates that you are performing a single element comparison on x array. If you want to perform element-wise operation, using a map is preferable.

2 Comments

Thank you very much. it worked :) I also changed my program by getting help from other comments y=[] for x in t: y.append(f(x)) plt.plot(t, y) it also worked
Welcome. Yes, there exist many solutions.
0

t is an array, you need to pass its element instead of the array itself.

for x in t
    plt.plot(x, f(x))

By the way, you will need to fix your function as well:

def f(x):   
    if x<=5:
        return (8*x)
    else:
        return (50*x)

3 Comments

both answers are completely correct... really bad behavior...
Have you run this? It will produce an empty graph...
Thank you for your response, really appreciate it. but the program is producing empty plot. Can you please tell me why? thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.