MATLAB: Importing data from text file that is seperated by text

data importMATLABtext file

I have this text file that is of the following nature:
DATA 1
X Y
1 2
2 3
DATA 2
X Y
1 2
2 3
I want to import the X and Y data of each Data group into MATLAB. My problem is that I want to do this with different text files, which all have the same general format, but will have differing number of data points. Is there a way to import the data without having to write specific code for each text file?

Best Answer

  • This is easy with textscan, then you can simply call it twice to get both blocks of data:
    fid = fopen('temp.txt','rt');
    Grp1 = textscan(fid,'%f%f','HeaderLines',3);
    Grp2 = textscan(fid,'%f%f','HeaderLines',3);
    fclose(fid);
    reads all the data of the attached file (see below), and produces these values:
    >> cell2mat(Grp1)
    ans =
    1 2
    3 4
    >> cell2mat(Grp2)
    ans =
    5 6
    7 8
    This works because textscan reads all of the data that matches its format string until the first line that does not match. Then, because we do not close the file, we can simply call textscan again to continue reading from that line, so it continues to read the next group of data.
    If the number of points/data-blocks varies or is large, then place this in a loop and put the values in a cell array, perhaps something like this:
    out = {};
    fid = fopen('temp.txt','rt');
    tmp = textscan(fid,'%f%f','HeaderLines',3);
    while ~isempty(tmp{1})
    out(end+1,:) = tmp; %#ok<SAGROW>
    tmp = textscan(fid,'%f%f','HeaderLines',3);
    end
    fclose(fid);
    which gives all of the data in a cell array:
    >> out
    out =
    [2x1 double] [2x1 double]
    [2x1 double] [2x1 double]
    >> out{3}
    ans =
    2
    4