gpt4 book ai didi

Python比较两行不同的矩阵

转载 作者:行者123 更新时间:2023-12-01 00:13:16 24 4
gpt4 key购买 nike

我只是想知道如何在 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-liner if dtype=int:

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

...或其他直接获取行索引的变体(查看 this post ):

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

关于Python比较两行不同的矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59486081/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com