extracting repeated strings line from text file
3 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
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
1 Comment
Stephen23
on 26 Jan 2016
See my other answer for a more versatile solution:
More Answers (0)
See Also
Categories
Find more on Text Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!