views:

71

answers:

2

Hi,

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!

+1  A: 

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
I also need the modular addition when multiplying two matrices
Yassin
@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
+4  A: 

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, multiplication modulo 2 can be done with "and".

>>> x & y
array([[0, 0],
       [0, 1]])
KennyTM
Thanks..........
Yassin