如何在MATLAB中将数据保存到.txt文件

6
我有三个txt文件s1.txt,s2.txt,s3.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
1个回答

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

非常感谢您,您的代码整洁有序,而且还能正常运行! :) 您让我今天过得很愉快!谢谢。 - Jessy
@Jessy:这段代码可以做得更好。我在输入部分没有给予足够的注意。例如,实际上你不需要使用cell2mat,只需在textscan中使用'CollectOutput'参数(true)即可。我还会添加验证代码,以确保所有输入文件具有相同的行数(否则代码将无法正常工作)。 - yuk
谢谢...我想知道为什么当我删除sortrows时,会出现这个消息-->“输入文件具有不同的行数”,而当我没有删除sortrows时,它就不会出现? - Jessy
@Jessy:这行代码还从单元数组中提取了双精度矩阵。如果你想去掉sortrows,可以加上 B = A {:}; - yuk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接