"cannot determine truth value of Relational" in summation

Question:

Trying to compute by hand a matrix determinant (I know the value is 28 and can be obtained by m.det()):

from sympy import symbols, Matrix, summation
i = symbols('i', integer=True)

m = Matrix([[3,  2, -1],
            [2, -1, -3],
            [1,  3, -2]])

D = summation(m[i,0]*m.cofactor(i,0), (i, 0, 2))

It raises:

File ... sympymatricesmatrices.py:140 in minor_submatrix  
    return _minor_submatrix(self, i, j)  
File ... sympymatricesdeterminant.py:890 in _minor_submatrix  
    if i < 0:  
File ... sympycorerelational.py:511 in __bool__  
raise TypeError("cannot determine truth value of Relational")  
    TypeError: cannot determine truth value of Relational

Pinpointing:

summation(m[i,0], (i, 0, 2)) # Works
summation(m.cofactor(i,0), (i, 0, 2)) # Raises the error

I’m lost.

Asked By: mins

||

Answers:

The problem is m.cofactor(i,0), specifically the i. By looking at the traceback:

    859 def _minor_submatrix(M, i, j):
    860     """Return the submatrix obtained by removing the `i`th row
    861     and `j`th column from ``M`` (works with Pythonic negative indices).
    862 
   (...)
    883     cofactor
    884     """
--> 886     if i < 0:
    887         i += M.rows
    888     if j < 0:

one can guess that the arguments to m.cofactor must be integer numbers, not symbols. So, we need to rethink how to obtain the result you are looking for. A simple list comprehension should be enough for this case:

# here, the i variable takes numerical values
sum([m[i,0] * m.cofactor(i, 0) for i in range(m.shape[0])])
# out: 28
Answered By: Davide_sd
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.