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...
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', ':');
2 Answers
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}
This is how I would do it:
fid = fopen('file.txt');
x = textscan(fid,'%s', 'Delimiter', char(10)); % read each line
fclose(fid);
x = x{1};
x = regexp(x, '\d*\.?\d*', 'match'); % extract numbers of each line
C = cellfun(@(t) reshape(str2double(t), 2, []).', x, 'UniformOutput', false); % rearrange
Result:
>> celldisp(C)
C{1} =
1.0e+03 *
2.867500000000000 1.101666666666670
2.555000000000000 0.764166666666667
2.382500000000000 1.221666666666670
2.115000000000000 0.759166666666667
1.845000000000000 1.131666666666670
1.270000000000000 0.991666666666667
C{2} =
1.0e+03 *
1.682666666666670 0.800333333333333
1.886000000000000 0.850333333333333
2.226000000000000 0.920333333333333
2.362666666666670 0.923666666666667
2.619333333333330 0.967000000000000
C{3} =
1.0e+03 *
1.029333333333330 0.513666666666667
1.236000000000000 0.753666666666667
C{4} =
1.0e+03 *
1.419333333333330 0.790333333333333
1.272666666666670 0.677000000000000