Create megred files via a for loop

조회 수: 1 (최근 30일)
Ivan Mich
Ivan Mich 2020년 5월 30일
답변: Voss 2024년 1월 7일
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

답변 (1개)

Voss
Voss 2024년 1월 7일
"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

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by