pythonmatrixsympyinequalityinequalities

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.

I know that singular elements for Sympy matrices can be compared via the following (for example the first element is compared):

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?


Solution

  • 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. 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! :)