ahajib
ahajib

Reputation: 13510

Python: Count similar elements of two matrices

So I have to adjacency matrices which are numpy 2D arrays and I want to count the number of similar elements between the two. This might sound silly and I know it can be done using a simple for loop but I am wondering if there is a oneliner to do so? Or maybe a faster way of doing it since I am dealing with large matrices. The following code is what I have now:

adj1 = graph1.get_adjacency()
adj2 = graph2.get_adjacency()

count = 0
for i in range(len(adj1)):
    for j in range(len(adj1)):
        if adj[i][j] == adj[i][j]:
            count += 1

Upvotes: 2

Views: 429

Answers (2)

Nate
Nate

Reputation: 76

If you wanted to be able to use the results of comparing adj1 and adj2, I suggest separating this into two lines:

test = np.equal(adj1,adj2)
count = sum(test[test == True])

But this will give you the same result as the accepted answer.

Upvotes: 1

HYRY
HYRY

Reputation: 97331

try this:

np.sum(adj1 == adj2)

if the dtype of adj1 and adj2 is float:

np.sum(np.isclose(adj1, adj2))

Upvotes: 3

Related Questions