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.

Sean
  • 17
  • 9
JSCOY
  • 21
  • 2

3 Answers3

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...

Dorian
  • 1,439
  • 1
  • 11
  • 26
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.

Quwsar Ohi
  • 608
  • 4
  • 12
  • 1
    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 – JSCOY Jul 21 '20 at 15:06
  • Welcome. Yes, there exist many solutions. – Quwsar Ohi Jul 21 '20 at 15:09
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)
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175