3

How can I define in numpy a matrix that uses operations modulo 2?

For example:

0 0       1 0       1 0
1 1   +   0 1   =   1 0

Thanks!

yassin
  • 6,529
  • 7
  • 34
  • 39

2 Answers2

10

This operation is called "xor".

>>> import numpy
>>> x = numpy.array([[0,0],[1,1]])
>>> y = numpy.array([[1,0],[0,1]])
>>> x ^ y
array([[1, 0],
       [1, 0]])

BTW, (element-wise) multiplication modulo 2 can be done with "and".

>>> x & y
array([[0, 0],
       [0, 1]])
cdf
  • 478
  • 1
  • 4
  • 11
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
2

You could subclass numpy.ndarray and override the __add__ method, but I think it would be far simpler to just be explicit. For example:

import numpy as np
x = np.array([[0,0],[1,1]])
y = np.array([[1,0],[0,1]])

print (x + y) % 2

Which yields:

array([[1, 0],
       [1, 0]])
Joe Kington
  • 275,208
  • 71
  • 604
  • 463
  • I also need the modular addition when multiplying two matrices – yassin Sep 15 '10 at 18:26
  • @Yassin - Then just do `(x * y) % 2`. Kenny's solution is the way to go, though... I tend to forget that xor and the like exist! It's a cleaner way to do what you want. – Joe Kington Sep 15 '10 at 18:32