Matlab将一个txt文件拆分为多个文件
我有一个像这样的.txt文件,它是制表符分隔符Matlab将一个txt文件拆分为多个文件,matlab,file-io,split,Matlab,File Io,Split,我有一个像这样的.txt文件,它是制表符分隔符 nr Time Lx Ly Lz Rx Ry Rz Mark 1 32874.4114 0.4 -0.2 0.7 0.2 0 -0.7 0 2 32874.4213 0.4 -0.2 0.4 0.2 0 -0.7 0 3 32874.4313 0.4 -0.2 0.4 0.2 0 -0.9 1 4 32874.4413 0.4 -0.2 0.4 0.2
nr Time Lx Ly Lz Rx Ry Rz Mark
1 32874.4114 0.4 -0.2 0.7 0.2 0 -0.7 0
2 32874.4213 0.4 -0.2 0.4 0.2 0 -0.7 0
3 32874.4313 0.4 -0.2 0.4 0.2 0 -0.9 1
4 32874.4413 0.4 -0.2 0.4 0.2 0 -0.9 0
5 32874.4514 0.2 -0.2 0.4 0.2 0 -0.9 1
6 32874.4613 0.2 -0.2 0.4 0.2 0 -0.9 0
7 32874.4713 0.2 -0.2 0.4 0.2 0 -0.9 1
8 32874.4813 0.2 -0.2 0.7 0.2 0 -0.9 0
我想使用Matlab来编码,并根据标记将这个.txt拆分为三个单独的.txt文件(当detectMark=1
时,然后将其拆分为一个新的.txt文件)
代码如下:
function splitdata(filename)
thelist=find(filename(:,9)==1)
thelist=[1; thelist];
n=length(filename);
m=length(thelist)
for i=2:m
out=zeros(thelist(i-1)-thelist(i),9);
out=filename(thelist(i-1):thelist(i)-1,:);
thename=['output' num2str(i-1,'%03i') '.txt']
dlmwrite(thename,out,'\t');
end
if thelist(m)<n
out=filename(thelist(m):n,:);
thename=['output' num2str(m,'%03i') '.txt']
dlmwrite(thename,out,'\t');
end
函数拆分数据(文件名)
列表=查找(文件名(:,9)==1)
列表=[1;列表];
n=长度(文件名);
m=长度(列表)
对于i=2:m
out=零(列表(i-1)-列表(i),9);
out=filename(列表(i-1):列表(i)-1,:);
名称=['output'num2str(i-1,'%03i')'.txt']
dlmwrite(名称,out,“\t”);
结束
如果列表(m),下面的解决方案应该可以做到这一点(至少对于上面的简化版本是如此)
fi = fopen('myFile.txt','r');
fileCount = 1;
fo = fopen(['output',num2str(fileCount),'.txt'],'w');
header = fgets(fi);
fprintf(fo,header);
tline = header;
first = true;
mark_index = 8;
while ischar(tline)
if (~first)
values = cell2mat(textscan(tline,'%f '));
if values(mark_index) == 1
fclose(fo);
fileCount = fileCount+1;
fo = fopen(['output',num2str(fileCount),'.txt'],'w');
fprintf(fo,header);
end
fprintf(fo,tline);
tline = fgets(fi);
else
first = false;
tline = fgets(fi);
end
end
fclose(fo);
fclose(fi);
它将逐行读取原始文件并查找标记,如果它看到标记设置为1,它将创建一个新的输出文件并关闭旧文件。这将一直重复,直到原始文档中没有更多的文件
它还将放置相同的“标题”创建所有输出文件。您可以从阅读以下函数的文档开始:fopen
、regexp
和str2double
。在我看来,这里有两个问题:如何读取/写入数据,以及如何根据“标记”将矩阵拆分为多个较小的矩阵。您应该向我们展示您迄今为止尝试过的内容,以及您遇到的问题。。使用textread
使用\t
分隔符读入字符。之后,使用Mark
查找您需要的行,然后可能使用arrayfun
分隔相应的行。之后,使用fopen
andfwrite
来写出新文件。祝你好运!当我尝试使用例如“dat=dlmread('output2.txt','\t')”时,出现了一个问题“文件和格式字符串不匹配”原始文件是制表符分隔符,但拆分后不再是。@user3737929循环根本不编辑行,因此如果它们以前是制表符分隔的,它们应该保持这样。