How to create multiple text files in a for loop?

조회 수: 7 (최근 30일)
Yildirim Kocoglu
Yildirim Kocoglu 2017년 12월 12일
답변: Naresh Pati 2020년 2월 8일
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
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
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.

Naresh Pati
Naresh Pati 2020년 2월 8일
The code is very useful to handle multiple files in a single program using for loop. Thank you.

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by