I suppose not too many people need this, but I do. Consider a sympy matrix with some symbolic variables in it, generated by
import sympy
[x1,x2,x3,x4]=sympy.symbols(['x1','x2','x3','x4'])
A=sympy.Matrix([[x1,x2],[x3,x4]])
Now, say you want to populate this matrix with x1=x2=x3=x4=1. This is easy:
An=A.subs({x1:1,x2:1,x3:1,x4:1})
Convert to numpy array:
from pylab import array
B=array(An)
This works….., but we have an array of objects, not of floats! Hm… The sympy module gives us the evaluate expression function N:
B_float = array(sympy.N(An))
Hm… fails again, with the error “Not implemented for matrices” (or something like that). So what do we do now? Well, we can iterate over An and apply this to each element. The following function does the job:
def Sym2NumArray(F):
“”"Function to convert symbolic expression with numerical data to numpy array “”"
shapeF=shape(F)
B=zeros(shapeF)
for i in range(0,shapeF[0]):
for j in range(0,shapeF[1]):
B[i,j]=sympy.N(F[i,j])
return B
Enjoy