6

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],
         [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],
          [0],
          [4]],

        [[0],
         [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?

2
  • 1
    axis=through_rows? What is your expected output...? Commented Jan 20, 2017 at 10:35
  • 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. Commented Jan 20, 2017 at 10:40

1 Answer 1

10

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)
Sign up to request clarification or add additional context in comments.

1 Comment

For arrays with generic no. of dims, we could use axis=-1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.