Ask Your Question

# Convert a text file into a matrix

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

## 2 Answers

Sort by » oldest newest most voted

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

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?

( 2013-04-04 12:33:10 +0200 )edit

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

( 2013-04-04 12:42:36 +0200 )edit

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.

more

## Your Answer

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

Add Answer

## Stats

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

Seen: 1,084 times

Last updated: Apr 07 '13