Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

TypeError: x0 is not a valid variable trying to solve equation

I'm trying to convert a matrix into a set of equations and then use solve but hitting an error.

from sage.matrix.constructor import matrix
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing

# Define the matrix and vector
M = matrix(QQ, 3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
v = vector(QQ, [1, 2, 3])

# Augment the matrix with the vector
Maug = M.augment(v, subdivide=True)

# Create polynomial ring
P = PolynomialRing(QQ, 3, names="x")

# Calculate coefficient equations
coeff_eqns = (M * vector(P.gens())).list()

# Create equations
equations = []
for i in range(len(coeff_eqns)):
    eq = coeff_eqns[i] - v[i]
    equations.append(eq)

print(equations)
print(P.gens())

# Solve the equations
solution = solve(equations, P.gens())

generates this output

[x0 + 2*x1 + 3*x2 - 1, 4*x0 + 5*x1 + 6*x2 - 2, 7*x0 + 8*x1 + 9*x2 - 3]
(x0, x1, x2)

and this error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In [1], line 27
     24 print(P.gens())
     26 # Solve the equations
---> 27 solution = solve(equations, P.gens())

File /home/sc_serv/sage/src/sage/symbolic/relation.py:1046, in solve(f, *args, **kwds)
   1044     for i in x:
   1045         if not isinstance(i, Expression):
-> 1046             raise TypeError("%s is not a valid variable." % repr(i))
   1047 elif x is None:
   1048     vars = f.variables()

TypeError: x0 is not a valid variable.

Any thoughts?