Python包含两行不同的矩阵



我只是想知道如何在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

这里 x 是一个 2x4 矩阵,y_in 是一个 4x4 矩阵。 我只需要从 x 中剪切一行,并想将其与所有带有 y_in 的行进行比较。

假设您有一个形状 (n,m( 的矩阵a和一个形状 (m,( 的数组b,并且想要检查哪一行a等于b中的一行,您可以使用np.equal[docs] - 如果您的数据类型是整数。或者np.isclose[docs] 如果您的数据类型是 float ->

例:

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

。或作为 1 行,如果dtype=int

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

。或其他变体直接获取行索引(查看这篇文章(:

row_match = np.where((np.isclose(a, b)).all(axis=1))
# (array([1], dtype=int64),)

下面的代码可能会对您有所帮助。

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

相关内容

最新更新