How to create multiple text files in a for loop?
26 ビュー (過去 30 日間)
古いコメントを表示
So here is a little code that I have written to create multiple text files in a for loop.
I need to store each complete calculation done in for loop into separate text files.
It creates the text files but, there is something wrong in my code.
I am sure I am getting close to achieving what I want to do but...
Basically, I am trying to write [1,2] & [4,5] into 2 different text files or store all the calculations into separate text files but, I get [4,5] instead on both text files.
This is not the actual project that I am working but, it's similar & I figured I should start with something simple & use that to the more complex problem otherwise, it might take me longer.
Thanks in advance. Any help is appreciated.
clear;
clc;
A=[1,2,3];
B=[4,5,6];
C={A,B};
F(1,2)=zeros();
for ii=1:2
for i=1:length(C)
for j=1:2
D=C(i);
E=D{1,1};
F(1,j)=E(1,j);
file_name=['file' sprintf('%d',ii) '.txt'];
fileID=fopen(file_name, 'w+');
fprintf(fileID,'%2.0f',F);
fclose(fileID);
end
end
end
1 件のコメント
Stephen23
2017 年 12 月 12 日
編集済み: Stephen23
2017 年 12 月 12 日
It would be much simpler to make sprint define the complete name, rather than awkwardly concatenate its output as you do now:
file_name = sprintf('file%d.txt',ii);
But the main question is: why do you need so many loops? The cell array C contains two array, which can be iterated over using just one loop. What possible purpose do all of you other loops serve?
回答 (2 件)
Stephen23
2017 年 12 月 12 日
You have too many loops. Try this:
A = [1,2,3];
B = [4,5,6];
C = {A,B};
for k = 1:numel(C)
[fid,msg] = fopen(sprintf('file%d.txt',k),'wt');
assert(fid>=3,msg)
fprintf(fid,'%2.0f %2.0f',C{k}(1:2));
fclose(fid);
end
Which generates the two requested files.
0 件のコメント
Naresh Pati
2020 年 2 月 8 日
The code is very useful to handle multiple files in a single program using for loop. Thank you.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!