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

时间:2015-05-13 08:12:34

标签: matrix sympy symbolic-math polynomial-math

我试图将表达式分解,并将系数分离为矩阵形式,例如:

Generic

Factor sympy expression to matrix coefficients?密切相关,其中Wild符号与match(form)一起用于确定其矩阵形式的系数。但是,我无法使match(form)方法适用于以下内容。

  

为什么match(form)方法失败?

     

有什么干净的替代品来实现这一目标?

#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))

Setup

收集条款,直到矩阵形式明显。匹配表格:

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])

Desired

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

1 个答案:

答案 0 :(得分:1)

由于Dim dir As New DirectoryInfo("d:\input") Dim sw As New StreamWriter("d:\input\extract.txt") For Each fi As FileInfo In dir.GetFiles("views.txt") Dim sr As New StreamReader(fi.FullName) Dim root As String Dim child As String Dim substring As String While Not sr.EndOfStream Dim sLine As String = sr.ReadLine If sLine.Contains("USE [") Then root = sLine '.Substring(13) - 1 End If If sLine.Contains("CREATE VIEW") Then child = sLine '.Substring(19) - 1 End If If sLine.Contains("(''") Then substring = sLine End If sw.WriteLine(root) sw.WriteLine(child) sw.WriteLine(substring) End While sr.Close() : sr.Dispose() Next sw.Flush() : sw.Close() : sw.Dispose() 已在变量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)