What is the best way to convert a SymPy matrix to a numpy array/matrix
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.
This answer is based on the advices from Krastanov and asmeurer. This little snippet uses sympy.lambdify:
from sympy import lambdify
from sympy.abc import x, y
g = sympy.Matrix([[ x, 2*x, 3*x, 4*x, 5*x, 6*x, 7*x, 8*x, 9*x, 10*x],
[y**2, y**3, y**4, y**5, y**6, y**7, y**8, y**9, y**10, y**11]])
s = (x, y)
g_func = lambdify(s, g, modules='numpy')
where g
is your expression containing all symbols grouped in s
.
If modules='numpy'
is used the output of function g_func
will be a np.ndarray
object:
g_func(2, 3)
#array([[ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20],
# [ 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147]])
g_func(2, y)
#array([[2, 4, 6, 8, 10, 12, 14, 16, 18, 20],
# [y**2, y**3, y**4, y**5, y**6, y**7, y**8, y**9, y**10, y**11]], dtype=object)
If modules='sympy'
the output is a sympy.Matrix
object.
g_func = lambdify(vars, g, modules='sympy')
g_func(2, 3)
#Matrix([[2, 4, 6, 8, 10, 12, 14, 16, 18, 20],
# [9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147]])
g_func(2, y)
#Matrix([[ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20],
# [y**2, y**3, y**4, y**5, y**6, y**7, y**8, y**9, y**10, y**11]])
numpy.array(SympyMatrix.tolist()).astype(numpy.float64)
The native tolist
method to makes the sympy matrix into something nestedly indexed
numpy.array
can cast something nestedly indexed into arrays
.astype(float64)
will cast numbers of the array into the default numpy float type, which will work with arbitrary numpy matrix manipulation functions.
As an additional note - it is worth mentioning that by casting to numpy you loose the ability to do matrix operations while keeping sympy variables and expressions along for the ride.
EDIT: The point of my additional note, is that upon casting to numpy.array, you loose the ability to have a variable anywhere in your matrix. All your matrix elements must be numbers already before you cast or everything will break.