1

I just want to know how to compare one row of a matrix with all the rows of the other matrix efficiently in python.

x=np.array(([-1,-1,-1,-1],[-1,-1,1,1])) #Patterns to be stored
t=np.array(([1,1,1,1])) #test vector
w=0*np.random.rand(4,4)
x_col1=x[0:1].T #Transpose of the 1st row
x_col2=x[1:2].T #Transpose of the second row
w=w+x[0:1].T*x[0]
w=w+x[1:2].T*x[1]
y_in=t*w

Here x is a 2x4 matrix and y_in is a 4x4 matrix. I just need to cut a single row from x and want to compare it with all the rows with y_in.

Souvik Das
  • 29
  • 5
  • What do you mean by compare ? – Jad Dec 26 '19 at 09:07
  • I don't have priviledge to comment. This might help you. https://stackoverflow.com/questions/45263347/numpy-compare-all-vector-row-in-one-array-with-every-other-one-in-the-same-arra – farheen Dec 26 '19 at 09:18
  • I simply mean that whether a row of x is identical with any one of the rows of y_in or not. – Souvik Das Dec 26 '19 at 09:26

2 Answers2

1

Below code might help you.

x_row = 1 # Row Index of x you want to check 
i=0
for y_row in y_in:
    print('Row Number:',i+1,(x[x_row]==y_row).all())
    i+=1
1

Assuming you have a matrix a of shape (n,m) and an array b of shape (m,) and want to check which row of a is equal to a row from b, you could use np.equal [docs] - if your data type is integer. Or np.isclose [docs] if your data type is float ->

Example:

a = np.array([[1,4], [3,4]], dtype=np.float)
b = np.array([3,4], dtype=np.float)

ab_close = np.isclose(a, b)
# array([[False,  True],
#        [ True,  True]])

row_match = np.all(ab_close, axis=1)
# array([False,  True]) # ...so the second row (index=1) of a is equal to b

...or as a 1-liner if dtype=int:

row_match = np.all(a==b, axis=1)

...or another variant to get the row indices directly (check out this post):

row_match = np.where((np.isclose(a, b)).all(axis=1))
# (array([1], dtype=int64),)
FObersteiner
  • 22,500
  • 8
  • 42
  • 72