2
$\begingroup$

I'm attempting to save data dynamically into two .txt files while doing a do-loop for later use in LaTeX, but I get a problem with the formatting.

I used the following code:

    txt1 = OpenWrite["txt1.txt", FormatType -> StandardForm];
    txt2 = OpenWrite["txt2.txt", FormatType -> StandardForm];

    If[txt1 === $Failed && txt2 === $Failed, Print["failed to open the files"],

     Do[
    Write[txt1, i, i*i "$\pm$" 1/(i*i), i*i*i "$\pm$" 1/(i*i*i) "\\"] 
    Write[txt2, "\includegraphics[width=0.20\textwidth]{Fig_" <> ToString[i] <> "}.eps\\"], 

          {i, 1, 4}];
         Close["txt1.txt"] Close["txt2.txt"]]

But when I put to run the do-loop I get the following files:

txt1:

  • 1\$\pm\$\ \$\pm\$
  • 2\$\pm\$\ \$\pm\$
  • 3\$\pm\$\ \$\pm\$
  • 4\$\pm\$\ \$\pm\$

txt2:

  • \includegraphics[width=0.20 extwidth]{Fig_1}.eps\
  • \includegraphics[width=0.20 extwidth]{Fig_2}.eps\
  • \includegraphics[width=0.20 extwidth]{Fig_3}.eps\
  • \includegraphics[width=0.20 extwidth]{Fig_4}.eps\

I would like, with the aids of Mathematica, to write in both txt files the LaTeX code to use later in a table:

txt1:

  • 1 & 1*1 \$\pm\$ 1/(1*1) & 1*1*1 \$\pm\$ 1/(1*1*1) \\
  • 2 & 2*2 \$\pm\$ 1/(2*2) & 2*2*2 \$\pm\$ 1/(2*2*2) \\
  • 3 & 3*3 \$\pm\$ 1/(3*3) & 3*3*3 \$\pm\$ 1/(3*3*3) \\
  • 4 & 4*4 \$\pm\$ 1/(4*4) & 4*4*4 \$\pm\$ 1/(4*4*4) \\

txt2:

  • \includegraphics[width=0.20\textwidth]{Fig_1}.eps\\
  • \includegraphics[width=0.20\textwidth]{Fig_2}.eps\\
  • \includegraphics[width=0.20\textwidth]{Fig_3}.eps\\
  • \includegraphics[width=0.20\textwidth]{Fig_4}.eps\\

My do-loop is not only 4 obviously, it is more than 1000, I just put 4 to make it shorter.

$\endgroup$
1
$\begingroup$

Try this as your Do-loop:

Do[
  Write[txt1, i, " & ", i, "*", i, 
   "$\\pm$1/(", i, "*", i, ") & ", i, "*", i, "*", i,
    "$\\pm$1/(", i, "*", i, "*", i, ") \\\\"] ;

  Write[txt2, 
   "\\includegraphics[width=0.20\\textwidth]{Fig_" <> ToString[i] <> 
    "}.eps\\\\"],
  {i, 1, 4}];

The changes include adding quotes to all the literals, using commas to separate the variables from the strings and using two backslashes wherever one should be printed. Without the quotes on the asterisks, MMA will multiply. Without the commas, MMA will multiply. Without a semicolon after the first Write and after the first Close, MMA will multiply.

Also, you may want to print your error message if either file fails to open, instead of both. (Use || instead of &&.) To test your error message, try using an empty string ("") for one of the file names. Note that if one file opens and the other fails, the open file remains open.

$\endgroup$
  • $\begingroup$ thank you very much dear @LouisB, that definitely solved my problem $\endgroup$ – user115376 Mar 31 '17 at 20:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.