Search code examples
pythonmatlabnumpyxor

numpy Matlab equivalent of `bitxor` between to vectors of different sizes WITHOUT loop


Here is the matlab code :

A=[1,2,3,4];
B=[5,3];
bitxor(A,B')

it returns :

ans =

     4     7     6     1
     2     1     0     7

How do I do that with numpy without a loop ?


Solution

  • You want np.bitwise_xor.outer(B, A)

    Alternatively, A ^ B[:,np.newaxis] works, which is identical for 1D arrays. B[:,np.newaxis] produces an array with shape (2, 1), which broadcasts against A with shape (4,) to produce an output of shape (2, 4), as desired.