MATLAB Answers

How can I extract line numbers of text data?

35 ビュー (過去 30 日間)
Hello everyone. I have attached a .txt file (portion.txt) which contains a portion of my data. What I need is to create a script which will identify strings that correspond to pairs of x-y coordinates and return their line numbers. For instance, in the .txt file the first set of coordinates begins at line 3 and ends at line 138 (the number of those pairs is written above each set of coordinates, which at this case is 136). So the script should return those two numbers. Then this process should be done for the whole file. I suppose that the process can be repeated with loop since every next set of coordinates begins after 2 lines from the previous one. How can this be done? Thanks in advance.


Azzi Abdelmalek
Azzi Abdelmalek 2016 年 7 月 31 日
while ischar(l)
  3 件のコメント
Paschalis Garouniatis
Paschalis Garouniatis 2016 年 8 月 1 日
Thanks a lot Azzi for your response. It worked just fine.


その他の回答 (2 件)

dpb 2016 年 7 月 31 日
編集済み: dpb 2016 年 8 月 1 日
i=0; % loop counter
while ~feof(fid) % until we run out of data
i=i+1; % increment counter
n(i)=cell2mat(textscan(fid,'%d %*[^\n]',1,'headerlines',1));
d(i)=textscan(fid,'%f %f',n(i),'collectoutput',1); % read the section
fgetl(fid); % straighten out file pointer end of record
fid=fclose(fid); % done with file
You'll have a list of the sizes and a cell array of M sets of nx2 coordinates to do with as wish...
Running on the file here I get...having named the m-file portion.m
>> portion
>> n
n =
136 162
>> d
d =
[136x2 double] [162x2 double]
>> cumsum([[3 2+n(1:end-1)].' [2+n].']) % the start/stop positions from the lengths
ans =
3 138
141 302
  5 件のコメント
Paschalis Garouniatis
Paschalis Garouniatis 2016 年 8 月 3 日
Thank you very much for your help dpb.


Shameer Parmar
Shameer Parmar 2016 年 8 月 1 日
編集済み: Shameer Parmar 2016 年 8 月 1 日
Data = textread('portion.txt', '%s', 'delimiter', '');
LineIndex = {};
count = 1;
for i=1:length(Data)
if ~isempty(strfind(Data{i},' '))
temp_line = regexp(Data{i},' ','split');
LineIndex{count,1} = ['Begin at ',num2str(i+1)];
LineIndex{count+1,1} = ['End at ',num2str(i + str2num(temp_line{1}))];
Make sure that your file "portion.txt" is in current directory.
to check output just type "LineIndex"
LineIndex =
'Begin at 3'
'End at 138'
'Begin at 141'
'End at 302'
  2 件のコメント
Paschalis Garouniatis
Paschalis Garouniatis 2016 年 8 月 1 日
I ran your code and the cell LineIndex has two specific subcells which represend the 'End at' with two numbers instead of one.


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by