Matlab将一个文本文件拆分为多个文件

时间:2014-07-13 14:40:10

标签: 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 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编写代码,并根据Mark(当检测到Mark = 1时将此.txt文件分散到三个单独的.txt文件中,然后将其溢出到新的.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

问题是:在输出文件中,时间列,小数点后的数字丢失了...有人想知道如何保留小数点后的数字吗?

1 个答案:

答案 0 :(得分:0)

下面的解决方案应该可以解决问题(至少它适用于您上面提供的简化版本。

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,它将创建一个新的输出文件并关闭旧的输出文件。这将继续重复,直到原始文档中没有更多文件。

它还会将相同的“标题”放入所有创建输出文件中。

相关问题