I am solving a system of two equations with two variables z and x repeatedly in a cycle. At each step the solution is output into a file using Write function. I’ve pasted a part of the file below. Apart from the numerical data, it contains also other things, like curly brackets, symbols like z-> . But I need to make a file that contains only two columns of numerical data, nothing else. How can I do that?
{z -> -2.1337292689248377, x -> -1.0028011752012573}
{z -> -1.5494511566425633, x -> -1.0015118850013995}
{z -> 0.14651664469911463, x -> -622.9327284292021}
{z -> 2.3907571924477877, x -> -1.0037755798274968}
{z -> 3.928880270839741, x -> -52.74880957186027}
{z -> 5.2048915646949965, x -> -1.017772661581148}
{z -> 9.062107349506263, x -> -1.0515309552374674}
{z -> 10.152134293099394, x -> -1.0641971180448309}
{z -> 14.312077199555635, x -> -395.73358957571725}
A possible solution is to export your data into CSV file:
(NOTE: this is the way to do it on-fly in the loop, if you can wait till the loop terminates,then just use Export[“MyFile.csv”, Sol] )
(*Define a File Path and a File Name and Open it for writing, appending \
a new data to the end of the file *)
MyPath = "C:\MY_PATH\\Wolfram \\Mathematica\\";
MyFile = "MyFile.csv";
FileH = OpenAppend[(MyPath ~~ MyFile)];
(* Solving Some Equation 10 Times in a Loop*)
Do[
(* Solve a system of dummy equations.
{x,z}/. is used to remove the rule sign "->" from the output*)
Sol = {x, z} /.
NSolve[{x^2 + z^2 == RandomReal[1],
z == x^2 + 0.001 RandomReal[1]}, {x, z} \[Element] Reals];
(*Write CSV formated String into the File *)
WriteString[FileH, ExportString[Sol, "CSV", Alignment -> Left]]
, {10}];
(* Close the file*)
Close[FileH];
My equations are non-polynomial. Besides, they have 5 parameters p1 - p5 which are varied et each step of the cycle. That’s why I use FIndRoot instead of NSolve and I define function sol[…] with parameters.
In this case there is no expression like sol[…] = something. That’s why I could not figure out where to insert {x, z} /.
Hi Lev,
The fact that you are using FindRoot instead of NSolve doesn’t really matter, please see the following code:
(*Define File Path and File Name and Open it for writing appending \
new data to the end of the file *)
MyPath = "C:\\MyPath\\Wolfram \
Mathematica\\";
MyFile = "MyFile.csv";
FileH = OpenAppend[(MyPath ~~ MyFile)];
sol[p1_, p2_, p3_, p4_, p5_] := {x, z} /.
FindRoot[{Exp[p1 x] == p2 x, Exp[p3 z] == p4 z}, {{z, p5}, {x, p5}}]
(* Solving Some Equation in the Loop*)
Do[
(*{x,z}/. is used to remove rule sign "\[Rule]" *)
Sol = {sol[1, 5, 1, 4, 0]};
(*Write CSV formated String into the File *)
WriteString[FileH, ExportString[Sol, "CSV", Alignment -> Left]]
, {10}];
(* Close the file*)
Close[FileH];
Please notice, that this is only needed when you HAVE TO update the file on-fly in the loop, as Gianluca Gorni mentioned you can do it much easier outside the loop using Export[] with Table attribute