user572575
user572575

Reputation: 1049

Can I use xor on numpy matrices?

I have 2 numpy matrix like this.

matrix1

arr1 =
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  1.,  0.]])

matrix2

arr2 =
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  0.]])

I want to find similarity of these matrices. I think xor can be used on matrices. Xor operation should show where values are different and then I can count value 1 to calculate a percentage of similarity. I don't know how to use xor in python.

This code doesn't work: a = arr1 xor arr2 .

Upvotes: 6

Views: 13406

Answers (4)

john k
john k

Reputation: 6614

There is also the inbuilt function bitwise_xor

Upvotes: 3

Sandipan Dey
Sandipan Dey

Reputation: 23119

If you have binary ndarrays then you could use logical_xor() too:

np.logical_xor(arr1, arr2).sum()
# 2

Upvotes: 1

Radio Controlled
Radio Controlled

Reputation: 950

A XOR B means:

(A and not B) or (B and not A):

AxorB = (A>B)+(B>A)

... at least for Boolean arrays.

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477318

You can simply use arr1 != arr2 which results in:

>>> arr1 != arr2
array([[False, False, False],
       [False, False,  True],
       [False,  True, False]], dtype=bool)

and then use .sum() since int(False) is 0 and int(True) is 1:

>>> (arr1 != arr2).sum()
2

So there are two indices for which arr1[i,j] is not equal to arr2[i,j].

If you want to calculate the similarity (here defined as the number of elements that are the same) you can use:

>>> (arr1 == arr2).sum()/arr1.size
0.77777777777777779

so 77.77% of the elements are the same.

Upvotes: 11

Related Questions