Factor sympy expression to matrix coefficients?

六眼飞鱼酱① 提交于 2019-12-04 10:39:39
unutbu

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