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

江枫思渺然 提交于 2019-12-03 05:16:20

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.

Saullo G. P. Castro

I am answering here taking the advices from Krastanov and asmeurer. This little snippet uses lambdify from sympy:

from sympy import lambdify
g_func = lambdify( (x), g )

This seems to be the best way to achieve what the question is asking for.

 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.

Henry

From the SymPy-0.7.6.1_mpmath_ matrix docs, the tolist() method exists:

Finally, it is possible to convert a matrix to a nested list. This is very useful, as most Python libraries involving matrices or arrays (namely NumPy or SymPy) support this format:

B.tolist()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!