sympy:收集矩阵系数的符号?

sympy: Collect symbols for matrix coefficients?

我正在尝试分解一个表达式,并将系数分离为矩阵形式,这样:

密切相关,其中 Wild 符号与 match(form) 一起使用以确定其矩阵形式的系数。但是,我无法让 match(form) 方法为以下工作。

Why does match(form) method fail?

What are clean alternatives to accomplish this?

#Linear Interpolation function: V(x)
v_1, theta_1, v_2, theta_2, x, L = symbols("v_1, theta_1, v_2, theta_2, x, L")
a_1, a_2, a_3, a_4 = symbols("a_1, a_2, a_3, a_4", real=True)
V = a_1*x**0 + a_2*x**1 + a_3*x**2 + a_4*x**3
#Solve for coefficients (a_1, a_2, a_3, a_4) with BC's: V(x) @ x=0, x=L
shape_coeffs = solve([Eq(v_1, V.subs({x:0})), 
                      Eq(theta_1, V.diff(x).subs({x:0})), 
                      Eq(v_2, V.subs({x:L})), 
                      Eq(theta_2, V.diff(x).subs({x:L}))], 
                     (a_1, a_2, a_3, a_4))
V = V.subs(shape_coeffs)
#Factor to matrix
V = sympy.collect(sympy.expand(V), (v_1, theta_1, v_2, theta_2))

并收集术语直到矩阵形式明显。匹配表格:

C_1, C_2, C_3, C_4 = symbols("C_1, C_2, C_3, C_4", cls=Wild)
form = c_1*v_1 + c_2*theta_1 + c_3*v_2 + c_4*theta_2
mat_coeffs = V.match(form)
N = Matrix([C_1, C_2, C_3, C_4]).transpose()
N = N.subs(mat_coeffs)
v = Matrix([v_1, theta_1, v_2, theta_2])

与引用的问题不同,V.match(form)、returns None 而不是 dict() 包含 {C_1:f(x), C_2:f(x), C_3:f(x), C_4:f(x)}。为什么会失败? -- 通过检查,解决方案是显而易见的。

因为 collect(expand(V), ...) 已经将 V 显示为变量 v_1, theta_1, v_2, theta_2 中的线性多项式,而不是使用 V.match(form),也许是一种更简单、更直接的方法来获得系数是使用V.coeff方法:

N = sy.Matrix([V.coeff(v) for v in (v_1, theta_1, v_2, theta_2)]).transpose()

import sympy as sy
#Linear Interpolation function: V(x)
v_1, theta_1, v_2, theta_2, x, L = sy.symbols(
    "v_1, theta_1, v_2, theta_2, x, L")
a_1, a_2, a_3, a_4 = sy.symbols("a_1, a_2, a_3, a_4", real=True)
V = a_1*x**0 + a_2*x**1 + a_3*x**2 + a_4*x**3
#Solve for coefficients (a_1, a_2, a_3, a_4) with BC's: V(x) @ x=0, x=L
shape_coeffs = sy.solve([sy.Eq(v_1, V.subs({x:0})), 
                      sy.Eq(theta_1, V.diff(x).subs({x:0})), 
                      sy.Eq(v_2, V.subs({x:L})), 
                      sy.Eq(theta_2, V.diff(x).subs({x:L}))], 
                     (a_1, a_2, a_3, a_4))
V = V.subs(shape_coeffs)
V = sy.collect(sy.expand(V), (v_1, theta_1, v_2, theta_2))
N = sy.Matrix([V.coeff(v) for v in (v_1, theta_1, v_2, theta_2)]).transpose()
print(N)

产量

Matrix([[1 - 3*x**2/L**2 + 2*x**3/L**3, x - 2*x**2/L + x**3/L**2, 3*x**2/L**2 - 2*x**3/L**3, -x**2/L + x**3/L**2]])