How can I extract quickly the numbers separated my commas and parenthesis from a txt file?

6 views (last 30 days)
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
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.

Sign in to comment.

Accepted Answer

Dave B
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')
  1 Comment
Sim
Sim on 9 Aug 2021
Perfect! Many thanks @Dave B :) .... (sorry I should be more specific with 'quickly'... I meant a fast way to extract the data...)

Sign in to comment.

More Answers (1)

Wan Ji
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

Categories

Find more on Data Type Conversion 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!