MATLAB Answers


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

@km 님이 질문을 제출함. 10 Nov 2017
최근 활동 @km 님이 댓글을 추가함. 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
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

로그인 to comment.

답변 수: 2

Guillaume 님의 답변 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
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

Thanks alot; It is working perfectly.

로그인 to comment.

Mischa Kim 님의 답변 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

표시 이전 댓글 수: 1
I added that part just now in the question. It will have less confusion.
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));

로그인 to comment.

Translated by