[英]Create a separate log file for each iteration in a for loop
I just want to make a script which runs multiple files and stores their outputs in separate log files. 我只想创建一个运行多个文件的脚本,并将它们的输出存储在单独的日志文件中。
So I wrote the code by using diary
to generate the output, but the diary
function is only 1 log file and the output is updating in the same log file for remaining iterations. 所以我通过使用diary
来编写代码来生成输出,但是diary
函数只有1个日志文件,并且输出在同一个日志文件中进行更新以进行剩余的迭代。 In my testconfig_1
file, I have at present only print as the content. 在我的testconfig_1
文件中,我目前只打印作为内容。
Then I tried to use the fopen
method, with this I am getting multiple log files but I don't understand how I can put that data into the log file which I have created through fopen
after each run. 然后我尝试使用fopen
方法,我得到了多个日志文件,但我不明白如何将这些数据放入我每次运行后通过fopen
创建的日志文件中。
% with diary method
clear all;
diary on;
instring ='testconfig_';
for x = 1:3
fprintf ('Simulation on testconfig_%d \n' , x);
test = [instring num2str(x)];
run(test);
diary testconfig_(x).log;
end
% without diary method
clear all;
diary on;
instring ='testconfig_';
for x = 1:3
fprintf ('Simulation on testconfig_%d \n', x);
test = [instring num2str(x)];
run(test);
fid = fopen(sprintf('testconfig_%d.log',x),'w');
end
I wanted to get testconfig_1.log
, testconfig_2.log
, testconfig_3.log
and I wanted to print in_testconfig_1
, in_testconfig_2
, in_testconfig_3
respectively 我想获得testconfig_1.log
, testconfig_2.log
, testconfig_3.log
,我想分别打印in_testconfig_1
, in_testconfig_2
, in_testconfig_3
You are using command syntax to call the diary
function. 您正在使用命令语法来调用diary
函数。
% Command syntax
diary filename.log
% Equivalent function syntax
diary( 'filename.log' );
Notice that, when using command syntax, all arguments are treated as strings, despite not having any quote marks! 请注意,使用命令语法时,尽管没有任何引号,但所有参数都被视为字符串!
So when you do diary testconfig_(x).log
, the equivalent is 所以当你做diary testconfig_(x).log
,相当于
diary( 'diary testconfig_(x).log' );
All of your logs have the same filename, because x
is never evaluated as the loop variable, it's always just part of a string! 所有日志都具有相同的文件名,因为x
永远不会被评估为循环变量,它始终只是字符串的一部分!
You are trying to create the strings with the loop variable in the name, for this you cannot use command syntax. 您正在尝试使用名称中的循环变量创建字符串,因此您无法使用命令语法。
Instead, use function syntax like this: 相反,使用这样的函数语法:
filename = sprintf( 'diary testconfig_%d.log', x );
diary( filename ); % treat the filename variable as a variable, not a string
You don't have to declare the intermediate filename
variable, and there are other ways to create the filename
string, but I hope this demonstrates the issue. 您不必声明中间filename
变量,还有其他方法可以创建filename
字符串,但我希望这可以证明这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.