问题
Given a square matrix A, find all matrices X such that AX = XA. This is a particular case of a Sylvester equation (one of the form AX + XB = Q) when A = B and Q is the zero matrix. I know SciPy has a solver for this type of equations, however, since the zero matrix is always a solution to my equation, this solver just gives me this trivial solution.
There are infinite solutions to the equation AX = XA, so I'm actually looking for a way to find a basis of the space of solutions.
Here's my attempt for a little example I worked on paper:
import numpy as np
import scipy
from sympy import *
A = np.array([[-2, 1, 1],[3, -3, 0], [1, 0, -1]])
X = np.array([["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]])
Q = np.zeros_like(L)
var('a b c d e f g h i L S')
A = Matrix([[-2, 1, 1],[3, -3, 0], [1, 0, -1]])
X = Matrix([[a, b, c], [d, e, f], [g, h, i]])
M = A.multiply(X) - X.multiply(A)
M
I can't figure out a way to "extract" the coefficients of the matrix M. If I could do this, then I would have the coefficient matrix of a homogeneous system of linear equations and maybe then I could get a non-trivial solution or all the possible solutions to this problem.
回答1:
I solved it with the help you gave me but there are probably more efficient ways. I post it anyway in case it helps anybody. I hope I can extend this to bigger matrices in a more efficient way.
import numpy as np
import scipy
from sympy import *
from sympy import Matrix, lcm
var('x L S')
#L is the matrix given, I want to find all matrices that commute with it
L = Matrix([[-2, 1, 1],[3, -3, 0], [1, 0, -1]])
#S is a variable matrix
S = Matrix([[x**1, x**2, x**3], [x**4, x**5, x**6], [x**7, x**8, x**9]])
#I need to solve the equation M = 0 (M = LS - SL)
M = L.multiply(S) - S.multiply(L)
#I convert each entry to a polynomial and extract coefficients
B = []
for i in range(0,9):
b = poly(M[i]).all_coeffs()
B.append(b)
# Define a function to add zeros corresponding to missing variables
def trp(l, n):
return [0]*(n-len(l)) + l[:n]
# Add zeros at the beginning of every list
C = []
for i in range(0,9):
c = trp(B[i],10)
C.append(c)
#Function to remove last zero corresponding to constant term
def trp2(l,n):
return l[:n] + [0]*(n-len(l))
#"Good" list: with coefficients for all variables wanted
A = []
for i in range(0,9):
a = trp2(C[i],9)
A.append(a)
#Find null space of matrix
A = Matrix(A)
v = A.nullspace()
#one solution matrix
v[0] + v[1] + v[2]
#The matrix found is S = [[1,1,1],[3,0,0],[1,0,2]] which indeed satisfies that SL = LS.
来源:https://stackoverflow.com/questions/61214824/given-a-matrix-a-find-all-matrices-such-that-ab-ba