MathGroup Archive 2008

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Automating file names in exporting data

  • To: mathgroup at smc.vnet.net
  • Subject: [mg92541] Re: Automating file names in exporting data
  • From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
  • Date: Fri, 3 Oct 2008 06:42:22 -0400 (EDT)
  • Organization: The Open University, Milton Keynes, UK
  • References: <gc3j1v$s77$1@smc.vnet.net>

Ivan wrote:

> I have a table of data with and I want to write them to different
> files with associated file names
> "x<i>.dat"
> where <i> is the label for the column.
> 
> My question is how do I write the Export command so that I can iterate
> the name of the file with For loop for example.

Hi Ivan,

Among many other possible ways, the following expression will do what 
you want:

     Do[Export["x" <> ToString[i] <> ".dat", data[[All, i]]],
       {i, Length[Transpose@data]}
     ]

The do-loop iterates from 1 (implicitly defined) to the number of 
columns (given by the length of the transpose matrix, since Mathematica 
counts the number of elements of a list as the number of rows at the 
first level).

File names are built by concatenating (the <> sign) several strings of 
characters, the value of the iterator 'i' being converted into a string 
tanks to the function *ToString*.

Since we want to save the columns individually, the expression 
data[[All, i]] takes all the rows of a given column.

For instance,

In[1]:= data = Array[(#1 + 2 #2)^2 &, {3, 4}]

Out[1]= {{9, 25, 49, 81}, {16, 36, 64, 100}, {25, 49, 81, 121}}

In[2]:= Do[Export["x" <> ToString[i] <> ".dat", data[[All, i]]], {i,
   Length[Transpose@data]}]

In[3]:= FileNames["x*"]

Out[3]= {"x1.dat", "x2.dat", "x3.dat", "x4.dat"}

In[4]:= FilePrint[%[[1]]]

During evaluation of In[4]:=
9
16
25

HTH,
-- Jean-Marc


  • Prev by Date: Re: How do I create my own color gradient?
  • Next by Date: Re: How do I create my own color gradient?
  • Previous by thread: Re: Automating file names in exporting data
  • Next by thread: How do I create my own color gradient?