Subject: Read data file containing fractional numbers?
From: Edwin Woollett
Date: Fri, 20 May 2011 17:10:59 -0700
On May 20, 2011, Volker van Nek wrote:
--------------------------------
Hi Ted,
you can use functions from stringproc:
data.txt
1 0
2 -1/3
3 -1/2
4 -3/5
5 -2/3
(%i1) stream: openr("data.txt");
(%o1) #<FD-STREAM for "file /home/volker/data.txt" {C6A00D1}>
(%i2) display2d:false$
(%i3) stringdisp:true$
(%i4) lines:[]$
(%i5) while (line: readline(stream)) # false do lines: endcons(line, lines)$
(%i6) lines;
(%o6) ["","1 0","2 -1/3","3 -1/2","4 -3/5","5 -2/3",""]
(%i7) lines: delete("", lines);
(%o7) ["1 0","2 -1/3","3 -1/2","4 -3/5","5 -2/3"]
(%i8) strings: map(split, lines);
(%o8) [["1","0"],["2","-1/3"],["3","-1/2"],["4","-3/5"],["5","-2/3"]]
(%i9) numbers: fullmap(parse_string, strings);
(%o9) [[1,0],[2,-1/3],[3,-1/2],[4,-3/5],[5,-2/3]]
(%i10) 2*numbers;
(%o10) [[2,0],[4,-2/3],[6,-1],[8,-6/5],[10,-4/3]]
(%i11) close(stream);
(%o11) true
Some comments:
Of course display2d:false and stringdisp:true are not necessary.
The first and last line of the file was empty. Since parse_string cannot
parse an empty string it is necessary to delete these empty strings from the
list.
The split function splits at blanks by default but other delimiters are also
possible. See doc.
Volker van Nek
--------------------------
Thanks, Volker, for the interesting use of
functions from stringproc.lisp. I will experiment
and perhaps create a function which automates
these steps to handle routine access to data
files inside a Maxima session.
I am in the process of revising Ch. 2 of Maxima
by Example, which will be renamed
Plot, Read, Write, and Fit.
The hope is to have separate sections on
reading and writing data (as well as updating
the plot2d stuff).
Ted