Ask Your Question

Convert a text file into a matrix

asked 2013-04-02 05:42:35 -0600

jmcshan1 gravatar image

updated 2015-01-13 14:18:01 -0600

FrédéricC gravatar image

I have a file with a list of elements inside the square of a Quadratic field, i.e. QQ(sqrt[13])^2. The file looks like [[2 + sqrt[13],4 - 2*sqrt[13]],[2,sqrt[13]],...]. I want to import this file into a single matrix over the field, in the previous example F.<a> = QuadraticField(13). Currently, I read everything in as a string then convert to the matrix, but there must be an easier way to do this. I am somewhat new to python programming in general.

edit retag flag offensive close merge delete

2 answers

Sort by » oldest newest most voted

answered 2013-04-04 01:21:51 -0600

vdelecroix gravatar image

There is no direct way to do that. Nevertheless, you may use the command sage_eval to convert your string to a list of lists.

sage: my_string = '[[sqrt(2),sqrt(3)], [sqrt(5),sqrt(7)]]'
sage: matrix(sage_eval(my_string))
[sqrt(2) sqrt(3)]
[sqrt(5) sqrt(7)]
edit flag offensive delete link more


This does not seem to work with variable names, such as sage: my_string = '[[x, 3 - x],[x, 3+x]]' Is there a way to make sage_eval work with these variables?

jmcshan1 gravatar imagejmcshan1 ( 2013-04-04 05:33:10 -0600 )edit

Nevermind, I got it: sage_eval(my_string, locals={'x':x})

jmcshan1 gravatar imagejmcshan1 ( 2013-04-04 05:42:36 -0600 )edit

answered 2013-04-06 21:05:58 -0600

Eviatar Bach gravatar image

Alternatively, an uglier but safer method (preventing possible evaluation of malicious code),

my_string = '[[sqrt(2),sqrt(3)], [sqrt(5),sqrt(7)]]'
matrix(filter(None, [map(SR, filter(lambda s:not s.strip() == '', l)) for l in map(lambda x:x.split(','), my_string.replace('[', '').split(']'))]))

Replace SR with whatever ring/field you want to coerce the entries into.

edit flag offensive delete link more

Your Answer

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

Add Answer

Question Tools

1 follower


Asked: 2013-04-02 05:42:35 -0600

Seen: 662 times

Last updated: Apr 06 '13