将 sympy 表达式分解为矩阵系数?

Factor sympy expression to matrix coefficients?

我努力认真地查看文档,但一无所获。

我正在尝试将表达式中的项因式分解或消去为矩阵形式。我的问题似乎与多项式因式分解不同(因为我打算实现一个函数 phi(x,y,z) = a_1 + a_2*x + a_3*y + a_4*z

import sympy
from sympy import symbols, pprint
from sympy.solvers import solve

phi_1, phi_2, x, a_1, a_2, L = symbols("phi_1, phi_2, x, a_1, a_2, L")

#Linear Interpolation function: phi(x)
phi = a_1 + a_2*x
#Solve for coefficients (a_1, a_2) with BC's: phi(x) @ x=0, x=L
shape_coeffs = solve([Eq(phi_1, phi).subs({x:0}), Eq(phi_2, phi).subs({x:L})], (a_1, a_2))
pprint(shape_coeffs)
#Substitute known coefficients
phi = phi.subs(shape_coeffs)
pprint(phi)

这按预期工作,但是,我想将其分解为矩阵形式,其中:

我尝试了 factor()cancel()as_coefficient(),但都没有成功。在纸面上,这是一个微不足道的问题。我在 sympy 解决方案中缺少什么?谢谢。

一个有效的方法:作为答案

C_1, C_2 = symbols("C_1, C_2", cls=Wild)
N = Matrix(1,2, [C_1, C_2])
N = N.subs(phi.match(C_1*phi_1 + C_2*phi_2))
phi_i = Matrix([phi_1, phi_2])
display(Math("\phi(x)_{answered} = " + latex(N) + "\ * " + latex(phi_i)))

My first answer used phi.match(form) to find the coefficients, but that doesn't seem to work so well 。因此,我认为更好的方法是使用 phi = collect(expand(...)) 然后使用 phi.coeff 来查找系数:

import sympy as sy

phi_1, phi_2, x, a_1, a_2, L = sy.symbols("phi_1, phi_2, x, a_1, a_2, L")

phi = a_1 + a_2*x
shape_coeffs = sy.solve([sy.Eq(phi_1, phi).subs({x:0}), sy.Eq(phi_2, phi).subs({x:L})], (a_1, a_2))
phi = phi.subs(shape_coeffs)

phi = sy.collect(sy.expand(phi), phi_1)
N = sy.Matrix([phi.coeff(v) for v in (phi_1, phi_2)]).transpose()
print(N)

产量

Matrix([[1 - x/L, x/L]])