【问题标题】:Given a matrix A, find all matrices such that AB = BA给定一个矩阵 A,找出所有满足 AB = BA 的矩阵
【发布时间】:2026-01-19 08:10:01
【问题描述】:

给定一个方阵 A,找出所有满足 AX = XA 的矩阵 X。这是当 A = B 且 Q 是零矩阵时 Sylvester 方程(AX + XB = Q 形式之一)的特殊情况。我知道 SciPy 有这类方程的求解器,但是,由于零矩阵始终是我方程的解,所以这个求解器只是给了我这个简单的解。

方程 AX = XA 有无限解,所以我实际上是在寻找一种方法来找到解空间的基。

这是我在纸上写的一个小例子的尝试:

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

我想不出一种方法来“提取”矩阵 M 的系数。如果我能做到这一点,那么我将得到一个齐次线性方程组的系数矩阵,也许然后我可以得到一个非- 这个问题的简单解决方案或所有可能的解决方案。

【问题讨论】:

标签: python sympy


【解决方案1】:

我在您给我的帮助下解决了这个问题,但可能有更有效的方法。无论如何我都会发布它,以防它帮助任何人。我希望我能以更有效的方式将其扩展到更大的矩阵。

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.

【讨论】:

    【解决方案2】:
    import sympy as sp
    
    a = sp.Symbol('a')
    b =sp.Symbol('b')
    c =sp.Symbol('c')
    d =sp.Symbol('d')
    e =sp.Symbol('e')
    f =sp.Symbol('f')
    g =sp.Symbol('g')
    h =sp.Symbol('h')
    i =sp.Symbol('i')
    
    
    A = sp.Matrix([[-2, 1, 1],[3, -3, 4], [1, 7, -1]])
    X = sp.Matrix([[a, b, c], [d, e, f], [g, h, i]])
    M = A.multiply(X) - X.multiply(A)
    
    LSG = sp.solve(M)
    print(LSG)
    
    LSGM = sp.Matrix([[LSG[a],LSG[b],LSG[c]],[LSG[d],LSG[e],LSG[f]],[0,0,0]])
    
    LSGM - LSGM
    

    【讨论】: