MATLAB Answers

@km
0

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

@km
さんによって質問されました 2017 年 11 月 10 日
最新アクティビティ @km
さんによって コメントされました 2017 年 11 月 10 日
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 件のコメント

サインイン to comment.

2 件の回答

回答者: 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 件のコメント

@km
2017 年 11 月 10 日
Thanks alot; It is working perfectly.

サインイン to comment.


回答者: 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 件のコメント

@km
2017 年 11 月 10 日
I added that part just now in the question. It will have less confusion.
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
@km
2017 年 11 月 10 日
Thanks for the answer

サインイン to comment.



Translated by