Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing vectors to a file without using Export

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], 
   " "]
  ]
like image 959
asim Avatar asked Dec 01 '11 23:12

asim


1 Answers

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]
like image 119
Arnoud Buzing Avatar answered Dec 17 '22 01:12

Arnoud Buzing