MathGroup Archive 1997

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

Search the Archive

How to write efficiently a large matrix of real numbers to an ASCII file


Dear fellow Mathematica users,

This seems to be a very basic question and must have been asked many
times before, maybe it is in a FAQ, but I could not find it.

How to write efficiently a matrix of real numbers to an ASCII file such
that it can be read by a normal program (e.g. in Fortran or C)?

WRI suggests to use WriteMatrix:

WriteMatrix[filename_String,data_List,separator_String:"\t"] :=
  With[{myfile = OpenWrite[filename]},
    Scan[(WriteString[myfile,First[#]];
    Scan[WriteString[myfile,separator,#]&,Rest[#]];
    WriteString[myfile,"\n"])&,data];
    Close[myfile]]

which, however, does not write exponents in the standard "e" format.
Furthermore, WriteMatrix is very slow (try it on a matrix of 1000 x 10
real numbers!).

The exponents are written correctly if one uses FortranForm to write the
individual numbers:

WriteFMatrix[filename_String,data_List,separator_String:"\t"] :=
  With[{myfile = OpenWrite[filename]},
    Scan[(WriteString[myfile,FortranForm[First[#]]];
    Scan[WriteString[myfile,separator,
    FortranForm[#]]&,Rest[#]];
    WriteString[myfile,"\n"])&,data];
    Close[myfile]]

This is still very slow, however. Has anybody a faster suggestion? Maybe
by using Compile[]? 

I'd appreciate very much your suggestions.

Martin Heimann (martin.heimann at dkrz.de)


  • Prev by Date: Fwd: Re:Until -Reply -Reply
  • Next by Date: Re: Re: bug in Mathematica 3.0 ?
  • Previous by thread: simple PDF
  • Next by thread: Combining several pure functions into a single pure function