我有一个非对称矩阵,基本上我想比较对角相对的元素,如下所示:
如果对角相对的元素相等但符号相反,则保留元素的绝对值并将对角相对的值归零
如果不是这种情况,则两个元素之一为 0(但我们不知道哪个),因此取两者的绝对值。
完成后,转置矩阵的下三角形并将其添加到上三角形。
我想出了以下 python 循环:
for i in range(0, number_files):
for j in range(0, len(Identifier)):
for k in range(0,len(Identifier)):
if Matrix[i][j][k] == - Matrix[i][k][j]:
Matrix[i][j][k] = abs(Matrix[i][j][k])
Matrix[i][k][j] = 0
else:
Matrix[i][j][k] = abs(Matrix[i][j][k]) # one of this two
Matrix[i][k][j] = abs(Matrix[i][k][j]) # values is 0
Matrix[i] = np.tril(Matrix[i],0).transpose() + np.triu(Matrix[i],0)
但是,这非常慢,我想知道如何使用 numpy 改进它。
我知道我可以生成一个测试,例如:
test=np.isclose(Matrix.transpose(),-Matrix)
它将返回一个 bool 矩阵,但我不知道如何继续。
非常感谢您的帮助
最佳答案
让我们首先创建一个示例矩阵:
>>> a = np.random.randint(-3, 3, 100).reshape(10,10)
获取其上、下三角形:
>>> triu = np.triu(a)
>>> tril = np.tril(a)
请注意,triu
和 tril
的大小与 a
相同,但在三角形外部填充了零。
定义要修改的三角形,然后转置另一个。例如。修改上三角:
>>> tril = tril.T
按照您的建议,执行以下操作之一来创建适用于您的条件的掩码:
# For integer data
>>> mask = (triu == -tril) & (triu != 0)
# For real data
>>> mask = np.isclose(triu, -tril) & ~np.isclose(triu, 0)
请注意添加的新条件 (!= 0
),以避免 triu
和 tril
填充 0 的比较
。 mask
将包含 True
,其中上三角形 triu
中的元素与下三角形 tril
匹配。
实现您的条件:
# Second and abs part of the first condition
>>> a = np.abs(a)
# Set upper diagonal when matches lower diagonal to 0
>>> a[mask] = 0
关于python - 如何使用 numpy 比较多维数组的对角相对元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27197219/