将因子表达式表达为矩阵系数? [英] Factor sympy expression to matrix coefficients?

查看:120
本文介绍了将因子表达式表达为矩阵系数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图勤于阅读文档,却空无一物.

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

我正在尝试分解或消除矩阵形式的表达式中的项.我的问题似乎与多项式因式分解不同(因为我计划实现函数phi(x,y,z) = a_1 + a_2*x + a_3*y + a_4*z)

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 :

我尝试了factor()cancel()as_coefficient(),但均未成功.从表面上看,这是一个琐碎的问题.我在sympy解决方案中缺少什么?谢谢.

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.

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

推荐答案

我的第一个答案使用phi.match(form)查找系数,但在匹配许多Wild符号时 .因此,我认为一种更好的方法是使用phi = collect(expand(...))然后使用phi.coeff来找到系数:

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)

收益

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

这篇关于将因子表达式表达为矩阵系数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆