本文介绍了如何使用symPy和numPy将符号替换为矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试用方程式中的两个符号代替每个符号的矩阵形式.
I'm trying to substitute two symbols in my equation for the matrix form of each of them.
我创建了一个换向器函数,形成了我的表达式:
I created a commutator function which formed my expression:
t, vS, = sy.symbols('t, vS', commutative = False)
hS = t + vS
eta = myComm(t,hS)
dHs = myComm(eta,hS)
print dHs.expand()
产生我想要的正确表达:
yielding the correct expression I want:
2*t*vS*t + t*vS**2 - t**2*vS - 2*vS*t*vS - vS*t**2 + vS**2*t
所以现在我希望用矩阵替换符号t和vS,但是当使用subs时出现错误,"unhashable type:'list'",我认为这与矩阵的初始化或它们的初始化有关被适当替换,因为我对numPy和symPy都是新手.
So now I wish to substitute the symbols t and vS with matrices, however when using subs I get an error, "unhashable type: 'list'" I assume it has to do with my initialization of the matrices or how they should be properly substituted as I'm new to both numPy and symPy.
其余代码:
tRel = ([e0, 0],[0,e1])
vtmp = ([v0, v1],[v2,v3])
dHs = dHs.subs(t, tRel)
dHs = dHs.subs(vS, vtmp)
print dHs
推荐答案
也许使用 lambdify :
import sympy as sy
import numpy as np
from sympy.abc import x, y
z = ((x+y)**2).expand()
print(z)
# x**2 + 2*x*y + y**2
X = np.arange(6).reshape(2,3)
Y = np.arange(1,7).reshape(2,3)
f = sy.lambdify((x, y), z, 'numpy')
print(f(X, Y))
# [[ 1 9 25]
# [ 49 81 121]]
assert np.allclose(f(X, Y), (X**2 + 2*X*Y + Y**2))
这篇关于如何使用symPy和numPy将符号替换为矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!