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

2 views (last 30 days)
Sim
Sim on 9 Aug 2021
Commented: Wan Ji on 9 Aug 2021
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

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

Community Treasure Hunt

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

Start Hunting!