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

标签 file matlab file-io format text-files

我有 3 个 txt 文件 s1.txt, s2.txt, s3.txt。每个文件都有相同的格式和数据数量。我只想合并这 3 个文件的第二列文件合并为一个文件。在合并数据之前,我根据第一列对其进行了排序:

未排序的文件: 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);

编辑: 实际上,只将数字写入文件不需要 FPRINTF。使用 DLMWRITE相反:

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

关于file - 如何在 MATLAB 中将数据保存在 .txt 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2925623/

相关文章:

c++ - 用 C++ 打开 2 个数据文件

c++ - C++中的文件命名

matlab - 一次将一个数组中的元素添加到另一个数组

matlab - 计算矩阵的每条对角线之和

c# - 存储大量文本数据的最佳方式?

windows - 使用 powershell 和 cmd 创建带有定义的 .h 文件

c++ - 自定义二进制文件在 C++ 中触发 failbit

matlab - 滤波后低频移位

c++ - 内存满时文件读取失败

Java writeObject() 始终覆盖现有对象,从不追加?