-1

Im trying to solve a problem in which I am given 2 ndarray of booleans . one of shape (n,m,z), denote as A, and the other (n,m), denote as B. If I am thinking of the 3D array as an array of 'z' 2D arrays, I would like to check if for every i between 0 and z, there is at least one coordinate [x,y] that: A[x,y,i] == B[x,y] == 1.

for example: let A be

np.array([[[1,0,0],
                [0,1,0],
                [0,0,1]]
               ,
               [[0,1,0],
                [0,1,0],
                [0,1,0]],

               [[1,0,0],
                [0,1,0],
                [0,0,1]]])

and B be:

> [[1,0,0],
   [0,1,0],
   [0,0,1]])

The function should return True!

I need to solve it without any loops (just numpy tools)!

Thank you in advance.

Omri_sr
  • 9
  • 1

1 Answers1

0

You can use

(np.logical_and(a == 1, a == b).sum((1,2)) >= 1).sum() == a.shape[0]

np.logical_and(a == 1, a == b) gives you the boolean mask for every 2D row. sum((1,2)) gives the count of matches in each row. We don't care if it's 1 or more so we get the >= 1 and count them using sum(). This must be equal to the number of rows a.shape[0]

Edit: (1,2) are the axes we want to see equivalency for. In case axes are x,y,z then the sum should be over (0,1) instead of (1,2) which would correspond to x,y instead of y,z. However, the array a representation is made where z here is the first axis.

MYousefi
  • 978
  • 1
  • 5
  • 10