如何在 Octave 中创建具有 headers 和不同变量的文件?

How to create a file with headers and different variables in Octave?

我需要创建一个包含一些变量及其相应标题的文件。为此,我创建了一个数组,其中包含使它们大小相同的变量。为了保存或创建此文件,我尝试了很多方法,但它们无法正常工作。我先试了save blbl.txt V1 V2,没找到放headers的方法。所以我更改为 fprintf,正如我在 Matlab 论坛中找到的那样(我在 Octave 论坛中没有找到这样的示例),但是它的作用与所示示例不同。

V1 = [1 2 3];
V2 = [4 5 6];
V = [V1.' , V2.'];
fileID=fopen('Pin.txt','w');
fprintf(fileID,'%12s %13s\n','V1','V2');
fprintf(fileID,'%6.6f %13.6f\n',V);
fclose(fileID);

它打印 headers 和两列,但它首先打印 V1 的值,然后打印 V2 中的值。我的意思是:

V1 V2
1   2
3   4 
5   6

它应该是(这就是 Matlab 中应该发生的事情)

V1 V2
1   4
2   5
3   6

有人知道为什么会这样吗?或者如果在 Octave 中有更好的方法来做到这一点?

与 Matlab/Octave 中的往常一样,fprintf 采用 column-major order 中的值。所以你需要转置 V:

fprintf(fileID, '%6.6f %13.6f\n', V.');

fprintf(fileID, '%6.6f %13.6f\n', [V1; V2]);

做什么?在我看来,您只是想创建一个 csv 文件(好吧,用空格代替逗号)。

如果是这样,您可以使用与 csv 相关的函数。例如

pkg load io
C = vertcat( { 'V1', 'V2' }, num2cell( V ) );
cell2csv ( 'Pin.txt', C, ' ' );

无论如何,正如 Luis 也暗示的那样,输出以这种方式出现的原因如下(摘自 Matlab 文档)

If your function call provides more input arguments than there are formatting operators in the format specifier, then the operators are reused.

因为matlab和octave column-major-order(即下一个元素是'below',而不是'to the right'),如果你想'reuse'这个变量方式,你需要按照Luis的建议安排。

如果 matlab 产生了 'correct' 结果,那么这实际上是一个 matlab 错误,因为在这种情况下它应该与八度音阶一样,你不应该依赖在上面.