What is the best way to convert a SymPy matrix to a numpy array/matrix

Saullo G. P. Castro picture Saullo G. P. Castro · Jun 12, 2013 · Viewed 19.8k times · Source

I am not sure if the approach I've been using in sympy to convert a MutableDenseMatrix to a numpy.array or numpy.matrix is a good current practice.

I have a symbolic matrix like:

g = sympy.Matrix( [[   x,  2*x,  3*x,  4*x,  5*x,  6*x,  7*x,  8*x,   9*x,  10*x],
                   [x**2, x**3, x**4, x**5, x**6, x**7, x**8, x**9, x**10, x**11]] )

and I am converting to a numpy.array doing:

g_func = lambda val: numpy.array( g.subs( {x:val} ).tolist(), dtype=float )

where I get an array for a given value of x.

Is there a better built-in solution in SymPy to do that?

Thank you!

Answer

Turtles Are Cute picture Turtles Are Cute · May 27, 2016

This looks like the most straightforward:

np.array(g).astype(np.float64)

If you skip the astype method, numpy will create a matrix of type 'object', which won't work with common array operations.