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

조회 수: 5 (최근 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
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 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
You'd then modify the main code to:
for step = 1:10
boundary(sprintf('result_%02d.txt', step));
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
movefile('result.txt', sprintf('result_%02d.txt', step));
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));

댓글을 달려면 로그인하십시오.


Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by