Factor sympy expression to matrix coefficients?

佐手、 提交于 2019-12-06 07:02:01

问题


I have tried to be diligent in looking through documentation and am coming up empty.

I am trying to factor or eliminate terms in a expression to matrix form. My problem appears to differ from polynomial factoring (as I plan to implement a function 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)

This works as expected, however, I would like to factor this to matrix form, where :

I have tried factor(), cancel(), as_coefficient() with no success. On paper, this is a trivial problem. What am I missing in the sympy solution? Thanks.

A valid method: Taken as the answer

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


回答1:


My first answer used phi.match(form) to find the coefficients, but that doesn't seem to work so well when matching many Wild symbols. So instead, I think a better approach is to use phi = collect(expand(...)) and then use phi.coeff to find the coefficients:

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)

yields

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


来源:https://stackoverflow.com/questions/30112645/factor-sympy-expression-to-matrix-coefficients

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!