Numpy: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I know this error has been posted before but I am not sure how to proceed. I am wanting to write a function to return a square wave and then.

Here is my code:

def V_in(t):

    v  = np.floor(2*t)      

    if v % 2 == 0   
        V_in = 1
    else: 
        V_in = -1

    return V_in


t = np.arange(0,10,1000)

square_wave = V_in(tpoints)

plt.plot(tpoints, square_wave);

When I run it I get this error message:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I have found I can get it to work if I create a loop over all values of t and store them in an array but that doesn't work when I try to use it within a second function.

def f(V,t):
    return (V_in(t) - V)

Where V is an initial value. This second function is then used in the RK4 algorithm to solve for the voltage.

Upvotes: 0

Views: 355

Answers (1)

Sheldore
Sheldore

Reputation: 39042

Either you can use a for loop to change your array values or you can use a vectorized operation using np.where to make the changes all at once as follows. np.where(V%2==0, 1, -1) will assign 1 to the array values which are divisible by 2 and -1 to the values which are not.

def V_in(t):
    V  = np.floor(2*t)  
    V = np.where(V%2==0, 1, -1)
    return V


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

square_wave = V_in(t)

plt.plot(t, square_wave);

enter image description here

Upvotes: 1

Related Questions