Sympy: Collect symbols for matrix coefficients?

I am trying to decompose the expression and divide the coefficients into matrix forms so that:

Generic

Closely related to Expression of factor factor for matrix coefficients? where Wild symbols are used with match(form)to determine the coefficients for its matrix form. However, I cannot get the method match(form)to work for the following.

Why does match(form)method fail?

What are the net alternatives to achieve 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))

Setup

And collect terms until the shape of the matrix becomes apparent. To match the 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])

Desired

Unlike the question mentioned, V.match(form)returns No instead of the dict () containing {C_1:f(x), C_2:f(x), C_3:f(x), C_4:f(x)}. Why is this failing? - upon examination, the solution is obvious.

+2
1

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

All Articles