0

Why is the function defined as shown below not working? I am getting the error msg ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Thanks in advance.

import math
from math import sin, cos, exp, pi, sqrt
from matplotlib import pyplot as plt

def pulse(Amax,td,t):
    if t<=td:
        y = Amax*sin((pi/td)*t)
    else:
        y = 0
    return y

t = np.linspace(0,4*pi,100)
Amax=10
td=11/1000
plt.plot(t,pulse(Amax,td,t), 'r', label='pulse A=10,td=11')
JXB
  • 29
  • 5
  • Does this answer your question? [ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()](https://stackoverflow.com/questions/10062954/valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous) – TrebledJ Apr 15 '20 at 10:28

3 Answers3

2

In t <= td you are directly comparing a scalar with an array. That type of operation is ambiguous because it can't determine what a truth value should be.

Keith
  • 42,110
  • 11
  • 57
  • 76
0

ugly but works

i=0
y=zeros(N0); ti=zeros(N0)

for t in np.arange(0,tend,dt):
    ti[i]=t
    if t <= td:
        y[i]=amax*np.sin(wf*t)
    else:
        y[i]=0
    i+=1

------------

Maybe a slightly better code

trg = np.arange(0,tend,dt)   # start,stop,step
for i,t in enumerate(trg):
    if t <= td:
        y[i]=amax*np.sin(wf*t)
    else:
        y[i]=0
JXB
  • 29
  • 5
0

In plt.plot you give 2 arrays. its better to create array y beforehand using iterating over array t with suitable conditions or your function pulse should return an array. like

def pulse (Amax,td,t):
    y=[]
    for i in t:
        if i <= td:
            y.append(Amax*sin((pi/td)*i))
        else:
            y.append(0)
    return y

at last just use plt.plot(t,pulse(Amax,td,t), whatever you want here)