2010-05-27 88 views
6

我有3個txt文件s1.txt, s2.txt, s3.txt。每個文件都有相同的格式和數量的數據。我只想將每個文件的第二列合併到一個文件中。如何將數據保存在MATLAB中的.txt文件中

未分類文件:之前我結合數據,我如第一列排序它 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 

回答

10

先創建輸出矩陣,然後將其寫入文件。

這是新代碼:

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); 

編輯: 其實只寫編號,你不需要fprintf中的文件。使用DLMWRITE代替:

dlmwrite('RT.txt',C,'\t') 
+0

。非常感謝您......您的代碼非常整齊,它的工作原理! :)你剛剛度過我的一天!謝謝.. – Jessy 2010-05-28 01:03:57

+0

@Jessy:代碼可以做得更好。我沒有太注意輸入部分。例如,您實際上不需要cell2mat,只需在textscan中使用'CollectOutput'參數(true)即可​​。我還會添加驗證代碼以確保所有輸入文件具有相同數量的行(或代碼將不起作用)。 – yuk 2010-05-28 01:49:37

+0

@Jessy,當我訪問MATLAB時,我更新了代碼。 – yuk 2010-05-28 15:31:12

相關問題