Week in PSE

January 6, 2010

How to convert a sympy Matrix to numpy array

Filed under: Uncategorized — hdahlol @ 1:18 pm

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

Advertisement

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Theme: Silver is the New Black. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.