JXB
JXB

Reputation: 29

Simple Python Function with an if statement not working?

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

Upvotes: 0

Views: 57

Answers (3)

JXB
JXB

Reputation: 29

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

Upvotes: 0

Kasinath PS
Kasinath PS

Reputation: 46

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)

Upvotes: 0

Keith
Keith

Reputation: 43024

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.

Upvotes: 2

Related Questions