Ask Your Question
1

Convert a text file into a matrix

asked 2013-04-02 12:42:35 +0100

jmcshan1 gravatar image

updated 2015-01-13 21:18:01 +0100

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
3

answered 2013-04-04 08:21:51 +0100

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

Comments

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 12:33:10 +0100 )edit

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

jmcshan1 gravatar imagejmcshan1 ( 2013-04-04 12:42:36 +0100 )edit
1

answered 2013-04-07 04:05:58 +0100

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

Stats

Asked: 2013-04-02 12:42:35 +0100

Seen: 1,190 times

Last updated: Apr 07 '13