Create megred files via a for loop

1 view (last 30 days)
Ivan Mich
Ivan Mich on 30 May 2020
Answered: Voss on 7 Jan 2024
Hello,
I have a question. I have created a code which use a loop with two iterations. Each iteration creates 25 .txt files (as I said previously) , and with the use of the above code I megre them in one file.
D = 'absolute/relative path to where the files are saved';
N = 25; % number of files
C = cell(1,N);
for k = 1:N
F = fullfile(D,sprintf('m%u.txt',k));
C{k} = dlmread(F);
end
M = vertcat(C{:});
dlmwrite('final.txt',M,'\t')
But I would like to create one merged file after each Iteration. Do you know how yo make it?
I wrote this
for n=1:numel(element);
.......
FP=fopen(sprintf('m%g0.txt',i),'wt');
fprintf(FP,'%s\t',num2str(results));
fclose(FP);
end
How could I put in my code your suggested script ?
Thank you in advance

Answers (1)

Voss
Voss on 7 Jan 2024
"I would like to create one merged file after each Iteration"
If by "merged file" you mean a file containing the contents of all the files read so far, one way to do that is: instead of storing the files' contents in a cell array whose cells' contents will be vertcat-ed at the end, do the vertcat-ing as you go.
D = 'absolute/relative path to where the files are saved';
N = 25; % number of files
M = [];
for k = 1:N
F = fullfile(D,sprintf('m%d.txt',k));
M = [M; readmatrix(F)]; % readmatrix is recommended over dlmread
writematrix(M,sprintf('m%d0.txt',k),'Delimiter','\t'); % writematrix is recommmended over dlmwrite
end
Note that the files created by this code go into the current directory, not D. If you want them to go into D, then use fullfile to construct the output file names, e.g.:
for k = 1:N
% ...
writematrix(M,fullfile(D,sprintf('m%d0.txt',k)),'Delimiter','\t');
end

Community Treasure Hunt

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

Start Hunting!