nimafl nimafl - 2 years ago 68
Python Question

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

Answer Source

try this:

np.sum(adj1 == adj2)

if the dtype of adj1 and adj2 is float:

np.sum(np.isclose´╝ładj1, adj2))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download