How to merge .txt files from a loop using writematrix

조회 수: 3 (최근 30일)
Ivan Mich
Ivan Mich 2020년 6월 1일
답변: Ronit 2024년 9월 19일
Hello,
I have a problem with a code. I am making via aloop multiple .txt files. I would like to merge them to a final.txt file, via a for loop but I do not know how.
I am importing my code
for n=1:numel(st);
for i=1:size(nam);
FP=fopen(sprintf('m%g0.txt',i),'wt');
fprintf(FP,'%s\t',num2str(Results));
fclose(FP);
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{:});
FF = sprintf('final%u.txt',n);
dlmwrite(FF,M,'\t')
end
end
I have tried dlmwrite but it does not work.
command window shows me error:
Error using dlmread (line 62) The file 'C:\Users\HP\Desktop\P\m2.txt' could not be opened because: No such file or directory
Error in F (line 105) C{k} = dlmread(F);
Could you help me?

답변 (1개)

Ronit
Ronit 2024년 9월 19일
Hello Ivan,
The error message suggests that the file m2.txt does not exist at the specified path. This could be due to a mismatch in the file naming or path issues. Please look at the following approach:
D = 'absolute/relative path to where the files are saved';
N = 25;
for n = 1:numel(st)
for i = 1:size(nam)
filename = fullfile(D, sprintf('m%u.txt', i)); % Correct file naming
FP = fopen(filename, 'wt');
fprintf(FP, '%s\t', num2str(Results));
fclose(FP);
end
C = cell(1, N);
for k = 1:N
F = fullfile(D, sprintf('m%u.txt', k)); % Correct file naming
if exist(F, 'file')
C{k} = readmatrix(F, 'Delimiter', '\t');
else
warning('File %s does not exist.', F);
end
end
M = vertcat(C{:});
FF = fullfile(D, sprintf('final%u.txt', n));
writematrix(M, FF, 'Delimiter', '\t');
end
Please try to use "readmatrix" instead of "dlmread" as it is not recommended anymore. Following are the MATLAB’s documentation links for further information:
  1. "readmatrix" - https://www.mathworks.com/help/matlab/ref/readmatrix.html
  2. "dlmread" - https://www.mathworks.com/help/matlab/ref/dlmread.html
  3. "writematrix" - https://www.mathworks.com/help/matlab/ref/writematrix.html
I hope it resolves your query!

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by