How to read specific data from a text file

Hello,
I want to read the latitude and longitude values (Station and Epicenter) from the following text file.
...
...
Station 37.94 N 47.54 E Altitude 1699m Azimuth L 0 T 90 Vs30 406
Epicenter 37.99 N 48.15 E FD 28 Km Mb0 Ms0 Mw6 Mn0 ML6.2
...
...
I used the following code for reading geographic coordinate of station
fid=fopen(FileName,'r') ;
text1 = textscan(fid,'%s','Delimiter','','endofline','');
text1 = text1{1}{1};
SLa=regexp(text1,'Station[\s]+(\d*\.?\d+)','tokens') ;
SLa=str2double([SLa{:}])
SLo=regexp(text1,'Station[\s] N +(\d*\.?\d+)','tokens') ;
SLo=str2double([SLo{:}])
and I got the following results
SLa =
37.9400
SLo =
NaN
I think I missed something in line 6, could you please help me to fix it?
Thanks

 채택된 답변

Adam Danz
Adam Danz 2019년 5월 23일
편집: Adam Danz 2019년 5월 23일

1 개 추천

You should be able to pull both numbers out at the same time with this:
LaLoTokens = regexp(text1,'Station +(\d*\.?\d+) +N +(\d*\.?\d+)', 'tokens');
LaLo = str2double([LaLoTokens{:}{:}]);
% or (depending on how 'text1' is stored)
LaLo = str2double([LaLoTokens{:}]);
Here's a great site to put together regular expressions: https://regex101.com/

댓글 수: 2

Iman Baz
Iman Baz 2019년 5월 23일
Dear Adam,
Thank you for your prompt reply. that's worked.
Adam Danz
Adam Danz 2019년 5월 23일
Glad I could help! I always go directly to that regex101 website any time I need to work out an expression.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

madhan ravi
madhan ravi 2019년 5월 23일

1 개 추천

Simpler:
S=fileread(filename);
sscanf(S,'Station %f N %f')

카테고리

도움말 센터File Exchange에서 Dates and Time에 대해 자세히 알아보기

질문:

2019년 5월 23일

댓글:

2019년 5월 23일

Community Treasure Hunt

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

Start Hunting!

Translated by