How to create multiple text files in a for loop?
17 次查看(过去 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 中查找有关 Startup and Shutdown 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!