简体   繁体   English

如何访问Sympy中的所有矩阵元素并将它们与另一个矩阵进行比较(即大于或小于)?

[英]How to access all matrix elements in Sympy and compare them to another matrix (i.e. greater than or less than)?

I'm looking for a way to compare all elements in a matrix with another matrix of the same size in a while loop by using Sympy.我正在寻找一种方法,通过使用 Sympy 在 while 循环中将矩阵中的所有元素与另一个相同大小的矩阵进行比较。

I know that singular elements for Sympy matrices can be compared via the following (for example the first element is compared):我知道 Sympy 矩阵的奇异元素可以通过以下方式进行比较(例如比较第一个元素):

import sympy as sp
from sympy.interactive import printing
from sympy import Eq, solve_linear_system, Matrix 

s = Matrix([2, 2])
e = Matrix([1, 1])


while s[0] > e[0]: #This works
    print('Working')
else:
    print('Not working')

But I'm looking to compare all matrix elements with eachother.但我希望将所有矩阵元素相互比较。 I tried doing this code but I got an error:我尝试执行此代码,但出现错误:

import sympy as sp
from sympy.interactive import printing
from sympy import Eq, solve_linear_system, Matrix 

s = Matrix([2, 2])
e = Matrix([1, 1])


while s > e: #This does not work and gives an error
    print('Working')
else:
    print('Not working')

The error recieved is:收到的错误是:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-203350991a18> in <module>
      7 
      8 
----> 9 while s > e: #Works
     10     print('Working')
     11 else:

TypeError: '>' not supported between instances of 'MutableDenseMatrix' and 'MutableDenseMatrix'

Can someone please help guide me in the right direction?有人可以帮助指导我正确的方向吗?

It seems that the only way to do this to compare all elements in one matrix to another in Sympy you have to use a while loop.似乎唯一的方法是将一个矩阵中的所有元素与 Sympy 中的另一个矩阵进行比较,您必须使用 while 循环。 Refer to the code below to see how this works, I've used two matrices with three elements each so that you can see it really works this way regardless of the amount of elements.请参阅下面的代码以了解其工作原理,我使用了两个矩阵,每个矩阵具有三个元素,因此无论元素数量如何,您都可以看到它确实以这种方式工作。

import sympy as sp
from sympy.interactive import printing
from sympy import Matrix 

s = Matrix([2, 2, 2])
e = Matrix([1, 1, 1])

while (s[0, 0] >  e[0, 0]) and (s[1,0] >  e[1, 0]) and (s[2,0] >  e[2, 0]): #This works
    print('Working')
    break
else:
    print('Not working')

Hope this helps.希望这可以帮助。 Big thanks to @OscarBenjamin for the help in finding this solution!非常感谢@OscarBenjamin 帮助找到这个解决方案! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM