如何在Octave中使用变量文件名将结构保存到文件中?

mar*_*rco 5 struct file save octave

在Octave中,我想将结构保存到文本文件中,其中文件的名称在脚本的运行时期间被确定.用我的方法我总是得到一个错误:

expecting all arguments to be strings. 
Run Code Online (Sandbox Code Playgroud)

(对于固定的文件名,这可以正常工作.)那么如何使用变量文件名将结构保存到文件中?

clear all;
myStruct(1).resultA = 1;
myStruct(1).resultB = 2;
myStruct(2).resultA = 3;
myStruct(2).resultB = 4;

variableFilename = strftime ("result_%Y-%m-%d_%H-%M.mat", localtime(time()))

save fixedFilename.mat myStruct; 
% this works and saves the struct in fixedFilename.mat

save( "-text", variableFilename, myStruct); 
% this gives error: expecting all arguments to be strings
Run Code Online (Sandbox Code Playgroud)

Eri*_*ski 6

在 Octave 中,当使用 save 作为函数时,您需要执行以下操作:

myfilename = "stuff.txt";
mystruct = [ 1 2; 3 4]
save("-text", myfilename, "mystruct");
Run Code Online (Sandbox Code Playgroud)

上面的代码将创建一个 stuff.txt 文件,并将矩阵数据放在那里。

上面的代码仅在 mystruct 是矩阵时有效,如果您有一个字符串单元格,它将失败。对于那些,你可以推出自己的:

 xKey = cell(2, 1);
 xKey{1} = "Make me a sandwich...";
 xKey{2} = "OUT OF BABIES!";
 outfile = fopen("something.txt", "a");
 for i=1:rows(xKey),
   fprintf(outfile, "%s\n", xKey{i,1});
 end
 fflush(outfile);
 fclose(outfile);
Run Code Online (Sandbox Code Playgroud)