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 🙂

Advertisements

4 Comments »

  1. Hi I usually use:

    B_float = array( A.evalf(subs={x1:1,x2:1,x3:1,x4:1}) ).astype(float)

    Best,
    Pascal

    Comment by Pascal — November 10, 2010 @ 1:12 pm

  2. This works too:

    import numpy as np
    np.array(np.array(An), np.float)

    Comment by Bastian Weber — May 12, 2011 @ 8:47 pm

  3. Thanks a lot : ) But somehow it only worked after I didn’t use F[i,j] but F[i][j]

    Comment by chambi — July 31, 2012 @ 4:46 pm

  4. […] N needed another overload to take arrays. This seems to be true in Python SymPy as well. […]

    Pingback by Convert a Sympy Function into a Julia function | DL-UAT — January 19, 2015 @ 11:08 am


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 )

Google+ photo

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

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: