Re: Reading Formatted Data
- To: mathgroup at yoda.physics.unc.edu
- Subject: Re: Reading Formatted Data
- From: withoff (David Withoff)
- Date: Sun, 3 Jul 1994 18:33:00 -0500
> This is a note regarding my last message about reading in formatted > data into Mathematica. > > For example, if my data file looked like this: > > 49765 4 1250 > 98743223 89 > > with the first series in columns 1-6 with 3 decimal places, the second series > in columns 7-8 with no decimal, the next series in columns 9-13, with 2 decimal > places, (my real data file is much bigger, this is simply an example-- my file > was witten by someone else in Fortran), so this is to be read into a list that > looks like this: > > {{49.765, 4., 12.50}, {987.432, 23., .89}} > > (note the placement of decimals) Here are two approaches. 1) The string-manipulation approach: In[1]:= !!data 49765 4 1250 98743223 89 In[1]:= f[s_String] := With[{ss = StringJoin[s, Table[" ", {12 - StringLength[s]}]]}, Map[ToExpression, { StringJoin[StringTake[ss, 3], ".", StringTake[ss, {4, 6}]], StringJoin[StringTake[ss, {7, 8}], "."], StringJoin[StringTake[ss, {9, 11}], ".", StringTake[ss, {12, 13}]] } ] ] In[2]:= data = ReadList["data", Record] Out[2]= { 49765 4 1250, 98743223 89} In[3]:= data = Map[f, data] Out[3]= {{49.765, 4., 12.5}, {987.432, 23., 0.89}} 2) The scale-factor approach: In[4]:= g[s_String] := With[{ss = StringJoin[s, Table[" ", {12 - StringLength[s]}]]}, Map[ToExpression, {StringTake[ss, 6], StringTake[ss, {7, 8}], StringTake[ss, {9, 13}]}] {0.001, 1.0, .01} ] In[5]:= data = ReadList["data", Record] Out[5]= { 49765 4 1250, 98743223 89} In[6]:= data = Map[g, data] Out[6]= {{49.765, 4., 12.5}, {987.432, 23., 0.89}} There are lots of variations, but they will all require reading strings into Mathematica and processing the strings. You could also use MathLink. The MathLink approach is sort of fun, actually, especially if you already know about formatted reading in C. For an example of a fairly elaborate program (probably more elaborate than needed here, but a good place to start) for reading and writing data using MathLink, see Todd Gayley's column in the Spring 1994 Mathematica Journal, and the corresponding item on MathSource. Dave Withoff Research and Development Wolfram Research