# convert sage complex matrix into numpy matrix This post is a wiki. Anyone with karma >750 is welcome to improve it.

I want to convert a sage matrix with complex elements to a numpy (scipy) matrix. Then I want to manipulate the resulting matrix with commands from linalg.

I have some problem. For example consider the following lines

m=matrix([[I,2],[3,4]])
import numpy
npm=numpy.array(m)
from numpy import linalg
linalg.eig(npm)


the result is an error:

...
TypeError: function not supported for these types, and can't coerce safely to supported types


why does it not work?

('Sage Version 5.8, Release Date: 2013-03-15' on osx 10.6.8)

edit retag close merge delete

Sort by » oldest newest most voted This post is a wiki. Anyone with karma >750 is welcome to improve it.

If you switch your first line to

m=matrix(CC,[[I,2],[3,4]])


then it should work.

more

thanks for the answer. I still have the same problem if I try to convert a matrix given by the product of your matrix m and a complex value as for example m2=I*m. How can I solve this?

just tried that and it does work. I believe it is essentially the same problem. You need to choose the base ring as the complex numbers (not the default, which is the symbolic ring). This post is a wiki. Anyone with karma >750 is welcome to improve it.

Alternatively, use the numpy method

sage: m=matrix([[I,2],[3,4]])
sage: m.numpy()
array([[I, 2],
[3, 4]], dtype=object)


Edit: For using eig method, you can set the dtype explicitly.

sage: m.numpy(dtype='complex64')
array([[ 0.+1.j,  2.+0.j],
[ 3.+0.j,  4.+0.j]], dtype=complex64)
sage: import numpy
sage: from numpy import linalg
sage: linalg.eig(m.numpy(dtype='complex64'))
(array([-1.13871109+0.81860214j,  5.13871098+0.18139789j], dtype=complex64),
array([[ 0.86633128+0.j        ,  0.35430107+0.05644054j],
[-0.49325052-0.07857533j,  0.93342662+0.j        ]], dtype=complex64))

more

it does not work: m.numpy() is equal to numpy.array(m). the problem is that linalg.eig does not work on these matrices

eig is not working because of the dtype. You can, of course, specify the dtype explicitly.