不使用 Export 将向量写入文件

发布于 2024-12-19 06:09:11 字数 830 浏览 2 评论 0原文

我有兴趣将多个向量写入文件,以便每个向量在文件中形成一行,并在生成后立即写入文件。向量的元素需要用单个空格分隔,并且我不想在向量中包含 { } 括号。基本上,我想模仿 C 的 fprintf("file", "%f %f %f\n") 功能。

这就是我所拥有的。有更好的方法吗?

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"

基于精彩的 Riffle 函数,由 Arnoud 和 Mr. Wizard 提供,如下,我将其修改如下:

WriteVector[stream_, vector_] :=
 Apply[WriteString[stream, ##, "\n"] &, 
  Riffle[Map[NumberForm[#, ExponentFunction -> (Null &)] &, vector], 
   " "]
  ]

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], 
   " "]
  ]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

意中人 2024-12-26 06:09:11

也许是这个?

WriteVector[stream_, vector_] :=
  WriteString[stream, ##, "\n"] & @@ Riffle[vector, " "]

然后

fname = "c:\\users\\arnoudb\\test.out";

:然后

Do[WriteVector[fname, RandomReal[{0, 1}, 5]],{10}]

检查:

FilePrint[fname]

完成后关闭流:

Close[fname]

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]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文