extracting repeated strings line from text file

3 views (last 30 days)
I need to extract repeated strings' lines from the attached text file. For example there are 2 lines which start with "PG01" string in the data file. I need to extract 2nd and 4th column of these lines as follows;
array_PG01=[ 2621.231803 -16886.323981 -20336.445346; 4678.863852 -17810.095582 -19125.227353];
Which code gives me this array?
Thanks in advance.

Accepted Answer

Stephen23
Stephen23 on 25 Jan 2016
Edited: Stephen23 on 25 Jan 2016
fid = fopen('data.txt','rt');
str = fscanf(fid,'%c',Inf);
fclose(fid);
C = regexp(str,'^PG01( +\S+)+\s+$','lineanchors','tokens');
C = regexp(vertcat(C{:}),'\S+','match');
N = str2double(vertcat(C{:}));
the output variable is:
>> N
N =
2621.231803 -16886.323981 -20336.445346 -8.459625 11 7 6 134
4678.863852 -17810.095582 -19125.227353 -8.459167 11 7 6 131
You can pick whatever columns you need:
>> N(:,[1,2,4])
ans =
2621.231803 -16886.323981 -8.459625
4678.863852 -17810.095582 -8.459167

More Answers (0)

Community Treasure Hunt

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

Start Hunting!