I need to write output of a Mathematica expression (a list of equations) in a file. I use
WriteInput[fname_, var_, eqlist_] := Module[{str, leq},
str = OpenWrite[fname];
leq = Length[eqlist];
WriteString[str, "{"];
removebracketvar[x_] :=
StringReplace[StringReplace[ToString[x],{"["-> "","]"->"",","->""}],Whitespace->""];
(*write equations*)
Do[
WriteString[str,
removebracketvar[ToString[eqlist[[i]] , InputForm]] ];
WriteString[str , ";\n"] ,
{i, leq}];
WriteString[str, "}"];
Close[str]
]
This works fine for small coefficients, e.g.,
SetDirectory["/home/mydir"];WriteInput["sys1.txt",{x[1,1],x[2,1],x[1,2]},
{3.4x[1,1]^2,x[2,1]^2,x[1,2]^2}]
i.e., it generates the following file sys1.txt
{3.4*x11^2;
x21^2;
x12^2;
}
However, the problem comes up when 1. the coefficients are integer, e.g.,
SetDirectory["/home/mydir"];
WriteInput["sys1.txt", {x[1, 1], x[2, 1], x[1, 2]}, {3.0 x[1, 1]^2, x[2, 1]^2, x[1, 2]^2}]
which writes sys1.txt as
{3.*x11^2;
x21^2;
x12^2;
}
where '3.' is not appropriate for the later operations on the file by some other external code. 3.0 or 3 is what I want.
Coefficients in scientific form are also problematic. e.g.,
SetDirectory["/home/mydir"];
WriteInput["sys1.txt", {x[1, 1], x[2, 1], x[1, 2]},
{3.998723445*10^6 x[1, 1]^2, x[2, 1]^2, x[1, 2]^2}]
gives
{3.998723445*^6*x11^2;*x11^2;
x21^2;
x12^2;
}
where it has this weird *^ notation for the exponents. I want 10^(6) instead, or just in the non-scientific form, i.e., 3998723.445 is also fine.
Is there any good way of tweaking this short code to get the coefficients in the form I want?
csv/tsv/datfromtxtyou will get numbers of the form 3.998723445e6. I don't know if that is good enough for you. – mohit6up Apr 20 '12 at 21:06