How can I extract quickly the numbers separated my commas and parenthesis from a txt file?
4 views (last 30 days)
Show older comments
How can I extract quickly the numbers separated by commas and parenthesis from a txt file?
My data in the txt file are like these ones (please see attached the test.txt file):
(247, 4879) 507375.4469844637
(248, 6707) 434984.2860625947
(248, 7948) 454158.15272926027
(248, 8361) 17942.0
(249, 811) 161190.0
(250, 595) 148941.7522329302
(250, 6267) 141033.34299772125
As output, I would like a matrix with 3 columns like this:
247 4879 507375.4469844637
248 6707 434984.2860625947
248 7948 454158.15272926027
248 8361 17942.0
249 811 161190.0
250 595 148941.7522329302
250 6267 141033.34299772125
2 Comments
the cyclist
on 9 Aug 2021
It would be easier for us to help if you uploaded your text file, or a smaller representative text file.
Then we don't have to guess at the exact format of your file, and we can easily test a potential solution.
Accepted Answer
Dave B
on 9 Aug 2021
It's not the most elegant solution, but as you said 'quickly' :)
a=readmatrix('test.txt',"Whitespace",'(','Delimiter',{')' ','})
This says treat the open parentheses as whitespace, and the close parentheses as a delimiter (because you don't have one between the second and third columns.
Could also have done:
a=readmatrix('test.txt','Delimiter',{'(' ')' ','},'LeadingDelimitersRule','ignore')
More Answers (1)
Wan Ji
on 9 Aug 2021
It is quite easy to do so.
fid = fopen('a.txt','rt'); % a.txt is your file name
a = textscan(fid,'(%f, %f) %f');
a = cell2mat(a)
Then variable a is
2 Comments
See Also
Categories
Find more on String Parsing 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!