Ask Your Question
0

convert sage complex matrix into numpy matrix

asked 2013-05-06 20:45:13 +0200

this post is marked as community wiki

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 flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
1

answered 2013-05-06 20:53:52 +0200

this post is marked as community wiki

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.

edit flag offensive delete link more

Comments

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?

abc gravatar imageabc ( 2013-05-06 21:14:41 +0200 )edit

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).

fidbc gravatar imagefidbc ( 2013-05-06 21:21:03 +0200 )edit
2

answered 2013-05-06 22:08:00 +0200

this post is marked as community wiki

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))
edit flag offensive delete link more

Comments

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

abc gravatar imageabc ( 2013-05-07 08:43:52 +0200 )edit

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

ppurka gravatar imageppurka ( 2013-05-07 18:19:56 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2013-05-06 20:45:13 +0200

Seen: 1,649 times

Last updated: May 07 '13