Sympy - 矩阵的元素比较

问题描述 投票:0回答:1

是否有一种方便的方法来按元素比较两个大小相等的 SymPy 矩阵?

这就是我正在尝试的:

from sympy import Matrix

def element_wise_matrix_comparison(matrix1, matrix2):
    result_matrix = Matrix([[matrix1[i, j] == matrix2[i, j] for j in range(matrix1.shape[1])] for i in range(matrix1.shape[0])])
    return result_matrix

虽然这段代码按预期工作,但我想知道是否有更简洁或更有效的方法在 SymPy 框架内执行此任务。

python sympy
1个回答
0
投票

A
B
为两个符号矩阵。
A == B
将进行结构比较。
A.equals(B)
执行逐元素数学比较。

from sympy import *
from sympy.abc import s, t
A = Matrix([[s, t], [s**2, s+2*t]])
B = Matrix([[s, t], [s**2, Add(s, t, t, evaluate=False)]])
A, B

print(A == B) # False, because the last elements of the matrices are structurally different
print(A.equals(B)) # True
© www.soinside.com 2019 - 2024. All rights reserved.