'How can I calculate conditional counting for each entries of a tuple?

def Trigger(V1, P_T, N1, N2):       # N1 = N_W  # N2 = N_A 
    
    V = np.transpose(V1[:N1])
    c = 0
    
    for l in range(N2): # over number of antennas

        if ( sum( (np.array(V[l]) >= P_T ) ) >= 2 ):
            c = c + 1

    if(c >= 4):
        Trigger = 1
    else:
        Trigger = 0

        return Trigger

N_W = 50
N_A = 90
P_Th = 2.0 * 5.0 
for m in range(N_W):
    Q = [ np.float32( np.random.normal(0, 5.0, N_A) ) ] # working

    Q = [number**2 for number in Q]
    V_G.append(np.array(Q))
    Q.clear()

T = Trigger(V_G, P_Th, N_W, N_A)

So, basically, I have a tupple V1. After taking transpose (i.e. V), I want to calculate for each entry of V, i.e. V[1], V[2]...and so on, (each of these are 1D-arrays), how many numbers are there with value greater or equal to "P_T". However, I have been facing the following problem on compilation.

if ( sum( (np.array(V[l]) >= P_T ) ) >= 2 ):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

where am I committing the mistake?



Solution 1:[1]

We can diagnose the issue by first splitting up the line that is giving you the error to work out which bit is causing errors

if ( sum( (np.array(V[l]) >= P_T ) ) >= 2 ):

Which can be split up to be:

test = np.array(V[l]) >= P_T
if (sum(t) >= 2):

If we then inspect test we can see it is a numpy array of booleans. The error occurs because we are calling the built-in version of sum which does not accept this as the input.

In this case it is a simple fix, just use the numpy version of sum np.sum() to count how many elements are true in your boolean array:

if (np.sum(np.array(V[l] >= P_T)) >= 2):

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 QuantumMecha