简体   繁体   English

如何使用symPy和numPy替换矩阵的符号

[英]How to substitute symbol for matrix using symPy and 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

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. 所以现在我希望用符号替换符号t和vS,但是当使用subs我得到一个错误时,“unhashable type:'list'”我假设它与我的矩阵初始化或它们应该如何被正确替换有关因为我是numPy和symPy的新手。

The rest of the code: 其余代码:

tRel = ([e0, 0],[0,e1])
vtmp = ([v0, v1],[v2,v3])

dHs = dHs.subs(t, tRel)
dHs = dHs.subs(vS, vtmp)
print dHs

Perhaps use lambdify : 也许使用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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM