Labfans是一个针对大学生、工程师和科研工作者的技术社区。 论坛首页 | 联系我们(Contact Us)
MATLAB爱好者论坛-LabFans.com
返回   MATLAB爱好者论坛-LabFans.com > 其它 > 资料存档
资料存档 资料存档
 
 
主题工具 显示模式
旧 2019-12-10, 20:41   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 如何在MATLAB中的.txt文件中保存数据

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

更多&回答...
poster 当前离线   回复时引用此帖
 


发帖规则
不可以发表新主题
不可以发表回复
不可以上传附件
不可以编辑自己的帖子

启用 BB 代码
论坛禁用 表情符号
论坛启用 [IMG] 代码
论坛启用 HTML 代码



所有时间均为北京时间。现在的时间是 06:52


Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.