Re: formatted table output to ascii file
- To: mathgroup at smc.vnet.net
- Subject: [mg97678] Re: formatted table output to ascii file
- From: kuhlen at gmail.com
- Date: Wed, 18 Mar 2009 04:56:44 -0500 (EST)
- References: <gpnseu$gqd$1@smc.vnet.net>
On Mar 17, 6:02 am, kuh... at gmail.com wrote:
> For the life of me I just cannot figure out how to get Mathematica to
> produce nicely formatted (C or Fortran format) output of a 2D table of
> numbers to an ASCII file.
>
> Let's say I've got this table:
>
> {{-6., 0.0000243729, 0.0000759669, 0.00187499},
> {-2., 0.0613641, 0.0827868, 0.0831174},
> {0.4, 0.317162, 0.307924, 0.33977}}
>
> I'd like the resulting file to correspond to this C format string
> "%5.2f %10.3e %10.3e %10.3e\n", i.e. to look like this:
>
> -6.00 2.437e-05 7.597e-05 1.875e-03
> -2.00 6.136e-02 8.279e-02 8.312e-02
> 0.40 3.172e-01 3.079e-01 3.398e-02
>
> I tried Export["file.dat",table], but got this mess:
>
> -6. 0.00002437286669095962 0.0000759669270937278
> 0.0018749887943499436
> -1.9999999999999998 0.06136412066687522
> 0.08278680554897219 0.08311737741506361
> 0.40000000000000036 0.31716209930168276
> 0.3079237859649251 0.3397696229714295
>
> I also tried pre-formatting with something like
>
> newdata = Map[ToString[PaddedForm[#, {6, 4}]] &, table, {2}];
>
> but my mathematica-fu isn't good enough to generalize this to the
> desired format.
>
> Any help would be greatly appreciated!
>
> mike
With some more work I found a solution. For future reference here's
what I did:
- First, I defined two formatting functions:
(* this is equivalent to %7.4f in C *)
fmt1[x_] := PaddedForm[x, {5, 4}];
(* this is equivalent to %10.3e in C *)
fmt2[x_] :=
ScientificForm[x, 4, ExponentFunction -> (# &),
NumberFormat -> (Row[{PaddedForm[ToExpression[#1], {4, 3}],
If[ToExpression[#3] < 0, "e-", "e+"],
PaddedForm[Abs[ToExpression[#3]], 1, SignPadding -> True,
NumberPadding -> "0"]}] &)];
- Next I defined a function that takes a row of the table and creates
a formatted string utilizing the fmt1[] and fmt2[] functions.
toline[x_] :=
ToString[TableForm[{{fmt1[x[[1]]], fmt2[x[[2]]], fmt2[x[[3]]],
fmt2[x[[4]]]}}, TableSpacing -> {0, 1}]];
- Lastly I opened the output file, and used Map[] to apply toline[] to
every row and write out the resulting line.
fp = OpenWrite["file.dat"];
Map[(WriteString[fp, toline[#], "\n"]) &, table];
Close[fp];
- The output is of the desired form:
-6.0000 2.437e-05 7.597e-05 1.875e-03
-2.0000 6.136e-02 8.279e-02 8.312e-02
0.4000 3.172e-01 3.079e-01 3.398e-02
mike