6

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.

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
bynx
  • 760
  • 2
  • 8
  • 19

1 Answers1

4

Perhaps use 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))
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • That worked perfectly for numerical matrices! Thanks! Any idea how to achieve a the same goal but with (referencing your code above) X and Y being composed of symbols rather than numerical elements? – bynx Jun 03 '13 at 21:46
  • For that, use the [subs method](http://docs.sympy.org/dev/modules/core.html#sympy.core.basic.Basic.subs). – unutbu Jun 04 '13 at 00:12