[Solved] Matlab spilt one txt file to several files


This solution below should do the trick (at least it does for the simplified version you put above.

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

It will read the original file line by line, and look for a mark, if it sees the mark being set to 1, it creates a new output file and closes off the old one. This will keep repeating until there are not more files in the original document.

It will also place the same “header” into all create output files.

2

solved Matlab spilt one txt file to several files