У меня есть 3 txt файла s1.txt, s2.txt, s3.txt
.Each имеют тот же формат и количество данных. Я хочу объединить только второй столбец каждого из этих 3 файлов в один файл. Прежде чем я объединю данные, я отсортировал их согласно 1-му столбцу:
Файл UnSorted: s1.txt s2.txt s3.txt
1 23 2 33 3 22
4 32 4 32 2 11
5 22 1 10 5 28
2 55 8 11 7 11
Отсортированный файл: s1.txt s2.txt s3.txt
1 23 1 10 2 11
2 55 2 33 3 22
4 32 4 32 5 28
5 22 8 11 7 11
Вот код, который я имею до сих пор:
BaseFile ='s'
n=3
fid=fopen('RT.txt','w');
for i=1:n
%Open each file consecutively
d(i)=fopen([BaseFile num2str(i)'.txt']);
%read data from file
A=textscan(d(i),'%f%f')
a=A{1}
b=A{2}
ab=[a,b];
%sort the data according to the 1st column
B=sortrows(ab,1);
%delete the 1st column after being sorted
B(:,1)=[]
%write to a new file
fprintf(fid,'%d\n',B');
%close (d(i));
end
fclose(fid);
Как я могу получить вывод в новом txt файле в этом формате?
23 10 11
55 33 22
32 32 28
22 11 11
вместо этого формата?
23
55
32
22
10
33
32
11
11
22
28
11
Сначала создайте выходную матрицу, а затем запишите ее в файл.
Вот новый код:
BaseFile ='s';
n=3;
for i=1:n % it's not recommended to use i or j as variables, since they used in complex math, but I'll leave it up to you
% Open each file consecutively
d=fopen([BaseFile num2str(i) '.txt']);
% read data from file
A=textscan(d,'%f%f', 'CollectOutput',1);
% sort the data according to the 1st column
B=sortrows(A{:},1);
% Instead of deleting a column create new matrix
if(i==1)
C = zeros(size(B,1),n);
end
% Check input file and save the 2nd column
if size(B,1) ~= size(C,1)
error('Input files have different number of rows');
end
C(:,i) = B(:,2);
% don't write yet
fclose (d);
end
% write to a new file
fid=fopen('RT.txt','w');
for k=1:size(C,1)
fprintf(fid, [repmat('%d\t',1,n-1) '%d\n'], C(k,:));
end
fclose(fid);
EDIT: На самом деле, чтобы записать только числа в файл, вам не нужен FPRINTF. Используйте вместо этого DLMWRITE:
dlmwrite('RT.txt',C,'\t')