问题
I am trying to factor an expression, and separate coefficients to matrix form, such that:
Closely related to Factor sympy expression to matrix coefficients?, where Wild symbols are used with match(form)
to determine coefficients for its matrix form. However, I am unable to get the match(form)
method to work for the following.
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))
And collect terms until the matrix form is apparent. To match forms:
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])
Unlike the referenced question, V.match(form)
, returns None instead of a dict() containing {C_1:f(x), C_2:f(x), C_3:f(x), C_4:f(x)}
. Why does this fail? -- by inspection, the solution is obvious.
回答1:
Since collect(expand(V), ...)
already shows V
as a linear polynomial in the variables v_1, theta_1, v_2, theta_2
, instead of using V.match(form)
, perhaps an easier, more direct way to get the coefficients is to use the V.coeff
method:
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)
yields
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]])
来源:https://stackoverflow.com/questions/30209215/sympy-collect-symbols-for-matrix-coefficients