matlabtextimporttextscanread-text

Using textscan to extract values from a text file


I have the following text file:

  Leaf Tips:2867.5,1101.66666666667 2555,764.166666666667 2382.5,1221.66666666667 2115,759.166666666667 1845,1131.66666666667 1270,991.666666666667 
  Leaf Bases:1682.66666666667,800.333333333333 1886,850.333333333333 2226,920.333333333333 2362.66666666667,923.666666666667 2619.33333333333,967 
  Ear Tips:1029.33333333333,513.666666666667 1236,753.666666666667 
  Ear Bases:1419.33333333333,790.333333333333 1272.66666666667,677 

These are coordinates to regions of interest for each category in an image. I need to extract these regions. I know I have to use textscan to accomplish this but I am unsure of the formatspec options needed to achieve this, since whichever setting I use seem to give me some jumbled form of cell output.

What formatSpec should I use so that I get the coordinates of each region outputed in a cell?

I've tried the following:

file = '0.txt';
fileID = fopen(file);
formatSpec = '%s %f %f %f %f %f %f %f %f';
C = textscan(fileID, formatSpec, 150, 'Delimiter', ':'); 

Solution

  • Here's an example of what you can do:

    fid = fopen('0.txt');                    % open file
    T = textscan(fid, '%s','Delimiter',':'); % read all lines, separate row names from numbers
    fclose(fid);                             % close file
    T = reshape(T{1},2,[]).';                % rearrange outputs so it makes more sense
    T = [T(:,1), cellfun(@(x)textscan(x,'%f','Delimiter',','), T(:,2))]; % parse numbers
    

    Which will result in a cell array as follows:

    T =
    
      4×2 cell array
    
        {'Leaf Tips' }    {12×1 double}
        {'Leaf Bases'}    {10×1 double}
        {'Ear Tips'  }    { 4×1 double}
        {'Ear Bases' }    { 4×1 double}