Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I'd like to ask for better way to bitwise and over all elements in matrix rows.

I have an array:

import numpy as np
A = np.array([[1,1,1,4],   #shape is (3, 5) - one sample
              [4,8,8,16],
              [4,4,4,4]], 
              dtype=np.uint16)
B = np.array([[[1,1,1,4],  #shape is (2, 3, 5) - two samples
              [4,8,8,16],
              [4,4,4,4]], 
             [[1,1,1,4],
              [4,8,8,16],
              [4,4,4,4]]]
              dtype=np.uint16)

Example and expected output:

resultA = np.bitwise_and(A, axis=through_rows) # doesn't work 
# expected output should be a bitwise and over elements in rows resultA:
  array([[0],
         [4]])
resultB = np.bitwise_and(B, axis=through_rows) # doesn't work
# expected output should be a bitwise and over elements in rows
# for every sample resultB:
  array([[[0],
          [4]],
        [[0],
         [4]]])

But my output is:

resultA = np.bitwise_and(A, axis=through_rows) # doesn't work
  File "<ipython-input-266-4186ceafed83>", line 13
dtype=np.uint16)
SyntaxError: invalid syntax

Because, numpy.bitwise_and(x1, x2[, out]) have two array as input. How can I get my expected output?

it should be axis=1 -> I want to compute A[0,0] & A[0,1] & A[0,2] & A[0,3] for each row in sample. And expected outputs are under every example. – Jan Jan 20, 2017 at 10:40

The dedicated function for this would be bitwise_and.reduce:

resultB = np.bitwise_and.reduce(B, axis=2)

Unfortunately in numpy prior to v1.12.0 bitwise_and.identity is 1, so this doesn't work. For those older versions a workaround is the following:

resultB = np.bitwise_and.reduceat(B, [0], axis=2)
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.