Chandler Squires
Chandler Squires

Reputation: 407

Solving system of equations in sympy with matrix variables

I am looking for a matrix that solves a complicated system of equations; i.e., it would be hard to flatten the equations into vector form. Here is a toy example showing the error that I'm getting:

from sympy import nsolve, symbols, Inverse
from sympy.polys.polymatrix import PolyMatrix
import numpy as np
import itertools as itr

nnodes = 2
nodes = list(range(nnodes))
u_mat = PolyMatrix([symbols(f'u{i}{j}') for i, j in itr.product(nodes, nodes)]).reshape(2, 2)
u_mat_inv = Inverse(u_mat)
equations = [
    u_mat_inv[0, 0] - 1,
    u_mat_inv[0, 1] - 0,
    u_mat_inv[1, 0] - 0,
    u_mat_inv[1, 1] - 1
]
s = nsolve(equations, u_mat, np.ones(4))

This raises the following error:

TypeError: X must be a row or a column matrix

Is there a way around this without having to write the equations in vector form?

Upvotes: 0

Views: 90

Answers (1)

Oscar Benjamin
Oscar Benjamin

Reputation: 14530

I think nsolve is getting confused because u_mat is a matrix. Passing list(u_mat) gives the input as expected by nsolve. The next problem is your choice of initial guess is a singularity of the system of equations.

You can use normal solve here though:

In [24]: solve(equations, list(u_mat))
Out[24]: [(1, 0, 0, 1)]

Upvotes: 1

Related Questions