How to create multiple text files in a for loop?

42 views (last 30 days)
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 Comment
Stephen23
Stephen23 on 12 Dec 2017
Edited: Stephen23 on 12 Dec 2017
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?

Sign in to comment.

Answers (2)

Stephen23
Stephen23 on 12 Dec 2017
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 on 8 Feb 2020
The code is very useful to handle multiple files in a single program using for loop. Thank you.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!