loading integer or float data from file into a matrix

396 views
Skip to first unread message

myFalc

unread,
Jan 10, 2008, 11:42:26 AM1/10/08
to sage-devel
Hello!
I'm new to sage and I already searched for a solution on the web, but
couldn't find any.
At the moment I'm trying to load a file into sage and put its data
into a matrix. The file spans a matrix of thousands of float values.
columns separated by whitespaces and rows separated by newlines.
I was able to load the data into a string(or list) but i couldn't find
out how to put the data into a matrix.
e.g. M = Matrix(10,2,(string)) is not working.
anyone with ideas or solutions?

i used octave before, and it worked really easy there. unfortunately i
can't use the octave load commands in sage since there are semicolons
needed for the command which result in a syntax error.

greetings
markus

David Roe

unread,
Jan 10, 2008, 12:00:33 PM1/10/08
to sage-...@googlegroups.com
One way to do it is to use the Python functions on strings.  For example, if you want to use the real double field (RDF) and matrix_data is your string, the following should do what you want:
M = matrix(RDF, [b.split() for b in matrix_data.split('\n')])

The split method of a string creates a list of substrings that are separated by a given separator, and the default separator is whitespace.
See the documentation on RDF to see if you want to use that, or RR or something else.
David

boo...@u.washington.edu

unread,
Jan 10, 2008, 12:59:54 PM1/10/08
to sage-...@googlegroups.com
numpy saves the day.

import numpy
A = numpy.loadtxt('foo.data') #A is a float array
B = M.astype(int) #B is an int array

M = Matrix(RDF, list(A)) #M is a RDF matrix
N = Matrix(ZZ, list(B)) #N is an Integer matrix

Fernando Perez

unread,
Jan 10, 2008, 2:10:09 PM1/10/08
to sage-...@googlegroups.com
On Jan 10, 2008 10:59 AM, <boo...@u.washington.edu> wrote:
>
> numpy saves the day.
>
> import numpy
> A = numpy.loadtxt('foo.data') #A is a float array
> B = M.astype(int) #B is an int array
>
> M = Matrix(RDF, list(A)) #M is a RDF matrix
> N = Matrix(ZZ, list(B)) #N is an Integer matrix

Note that numpy arrays also have a .tolist() method, with 'smarter'
unpacking behavior:

In [16]: a = zeros((2,3))

In [17]: list(a)
Out[17]: [array([ 0., 0., 0.]), array([ 0., 0., 0.])]

In [18]: a.tolist()
Out[18]: [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]

It may be useful for some cases.

Cheers,

f

Harald Schilly

unread,
Jan 10, 2008, 2:50:05 PM1/10/08
to sage-devel
On Jan 10, 5:42 pm, myFalc <myf...@gmail.com> wrote:

> At the moment I'm trying to load a file into sage and put its data
> into a matrix.

a more general question, at the top of the sage notebook on the left
is the "data" dropdown menu. what exactly does it? also including a
matrix or just a general file? where is this documented or just not
implemented so far?

h
Reply all
Reply to author
Forward
0 new messages