I am interested in writing multiple vectors to a file such that each vector forms one row in the file, and is written to the file as soon as it is generated. The elements of the vector need to be separated by a single space, and I do not want to include the { }
parentheses for the vector. Basically, I want to mimic the fprintf("file", "%f %f %f\n")
functionality of C.
Here is what I have. Is there a better way of doing this?
st1 = OpenWrite["C:\\junk\\mu.out", FormatType -> OutputForm];
vt = Table[
v = RandomReal[{0, 1}, 5];
For[j = 1, j <= Length[v], j++,
WriteString[
st1,
SequenceForm[NumberForm[v[[j]], ExponentFunction -> (Null &)],
" "]
]
];
Write[st1, ""];
v,
{200}
];
In[3]:= Close[st1]
Out[3]= "C:\\junk\\mu.out"
Based on the wonderful Riffle function, courtesy Arnoud and Mr. Wizard, below, I modified it as follows:
WriteVector[stream_, vector_] :=
Apply[WriteString[stream, ##, "\n"] &,
Riffle[Map[NumberForm[#, ExponentFunction -> (Null &)] &, vector],
" "]
]
Maybe this?
WriteVector[stream_, vector_] :=
WriteString[stream, ##, "\n"] & @@ Riffle[vector, " "]
and:
fname = "c:\\users\\arnoudb\\test.out";
then:
Do[WriteVector[fname, RandomReal[{0, 1}, 5]],{10}]
and check:
FilePrint[fname]
close stream when done:
Close[fname]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With