MATLAB Answers

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

16 views (last 30 days)
@km
@km on 10 Nov 2017
Commented: @km on 10 Nov 2017
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.

  0 Comments

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 10 Nov 2017
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.

More Answers (1)

Mischa Kim
Mischa Kim on 10 Nov 2017
@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 Comments

Show 1 older comment
Mischa Kim
Mischa Kim on 10 Nov 2017
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

Sign in to comment.

Sign in to answer this question.