Is it possible that we can save .m file results with different name each time of execution?

1 次查看(过去 30 天)
Hello everyone, I have a Boundary.m file which is storing few results in result.txt file. I want to run that Boundary.m file for 10 times. But I want to preserve my result.txt file for each execution. Normally if I run
for i=1:10
Boundary
end
Then offcourse my result.txt file is over written everytime. But what I want to have 10 different result.txt file for all the 10 execution.
Is it possible?
Thanks in advance, KM
PS: Its a geo file that I will use later on for creation of 10 different geometries by gmsh.

采纳的回答

Guillaume
Guillaume 2017-11-10
In my opinion, the best course of action is to modify the boundary.m function or script. Since it takes no arguments, it probably is a script, which I'd change into a function. You can then add an optional argument to that function which would be the file name to write to, so you'd have:
function boundary(filename)
if nargin == 0 || ~isempty(filename)
filename = 'result.txt'; %default filename if not specified
end
%...
end
You'd then modify the main code to:
for step = 1:10
boundary(sprintf('result_%02d.txt', step));
end
to create files result_01.txt, result_02.txt, ..., result_10.txt.
This is really how your code should be designed. Hardcoded values (inputs, filenames, etc.) are never a good idea. There will always be a time when you don't want to use these hardcoded values. They should always be inputs. If necessary, make them optional.
If for some reason modifying boundary.m is not an option, you can always rename the created file. You only have to modify your main loop:
for step = 1:10
boundary
movefile('result.txt', sprintf('result_%02d.txt', step));
end
But again, the first approach is a much better design.

更多回答(1 个)

Mischa Kim
Mischa Kim 2017-11-10
@km, take a look at the documentation here. Appending allows you to store all data in one and the same file vs 10 different ones.
  4 个评论
Mischa Kim
Mischa Kim 2017-11-10
Gotcha. How about (as an example)...
for ii = 1:10
fileID = fopen(['result', num2str(ii),'.txt'],'w');
fmt = '%5d %5d %5d %5d\n';
fprintf(fileID,fmt, magic(4));
fclose(fileID);
end

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Type Identification 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by