2

I'm trying to save the results of a huge Radia calculation. I evaluate the function in a loop at multiple locations.

To export the data my first approach was to fill a Table and use the Export function:

xdim := 500;
ydim := 500;
zdim := 500;

Output =Table[{0,0,0},xdim*ydim*zdim];

For[x = 0, x < xdim, x += 1,
  For[y = 0, y < ydim, y += 1,
    For[z = 0, z < zdim, z += 1,
      pos = {x*5, y*5, z*5};
      B = radFld[MagnetSystem, "b", pos];
      Output[[(x + y*xdim + z*(xdim*ydim)) + 1]] = Flatten[SetPrecision[{pos, B}, 5]];

Export["magfield.txt", Output, "Table"];

This gives me nice output like this:

0   10. 20. -0.044028   -1.9814e-11 2.8324e-11
5.  10. 20. -0.028009   0.070218    0.015292
10. 10. 20.  0.10334    0.017762    0.0011278

I want to increase the resolution of my output grid though, so I'd prefer to not create a huge stable to store the data and export it after the loop, but rather write directly to a file stream inside the loop. For that I found OpenWrite and Write functions:

xdim := 5000;
ydim := 5000;
zdim := 5000;

outstream = OpenWrite[SavePath <> "magfield.dat",FormatType -> OutputForm];

For[x = 0, x < xdim, x += 1,
  For[y = 0, y < ydim, y += 1,
    For[z = 0, z < zdim, z += 1,
      pos = {x*5, y*5, z*5};
      B = radFld[MagnetSystem, "b", pos];
      Write[outstream, pos[[1]], " ", pos[[2]], " ", pos[[3]], " ", B[[1]], " ", B[[2]], " ", B[[3]]];

Close[outstream];

I found that I had to set FormatType -> OutputForm to have Write output the whitespace correctly. But the data is still output in a ridiculous format:

10 20 15 0.00491794 -0.00165474 -0.00022539
10 20 20 0.0045596 -0.00143759 -0.00133733
10 20 25 0.00223249 -0.000712553 -0.00219482
                                  -6
10 25 -65 0.0000414138 -4.61924 10   0.0000149969
                                  -6
10 25 -60 0.0000493121 -5.92221 10   0.0000184975

How can I convince Write and/or OpenWrite to output the numbers in proper e notation. If that is not possible, is there a way to convert the numbers to Strings and replace the exponent with an "e" character?

1 Answers1

1

I managed to get e notation output by using

out = ExportString[Join[pos, B], "Table"];
out2 = StringReplace[out, "\n" -> " "];
Write[outstream, out2];

inside the loop.

Or, as per the comment by @george2079 above:

Write[outstream, CForm[pos[[1]]], " ", CForm[pos[[2]]], " ", CForm[pos[[3]]], " ", CForm[B[[1]]], " ", CForm[B[[2]]], " ", CForm[B[[3]]]];
  • I actually though to do FormatType -> CForm on the OpenWrite.. when you do that I don't readily see how to add spaces because CForm quotes the spaces. – george2079 Jul 27 '15 at 14:50