How to extract coordinate from the header files?

2 views (last 30 days)
Hi everyone.
I have 6 headerlines and then data. I want to extract the only the coordinate numbers in the first headerline.
Example data as below and also as attached
Lat: 6.4931, Lon: 99.6067, Parameter: z(m)
Depth (m): 22.45
Constituents included: m2 s2 k1 o1
Time start: 00:00, 1. 1.1993
Time step (min): 60.00
Time Series length (hours):236664
01-Jan-1993 00:00:00 -0.0946
01-Jan-1993 01:00:00 -0.3369
01-Jan-1993 02:00:00 -0.5110
01-Jan-1993 03:00:00 -0.5776
Please see the script below:
clc;clear all; close all;
delim = ' '; % space delimited
% delim = '\t'; % tab delimited
% delim = ','; % comma delimited
%Input File
fid=fopen('aa__file002.txt');
% A = textscan(fid,'%s %n','Delimiter',delim); % read file;
A = textscan(fid,'%s %s %f','HeaderLines',6); % read file;
Headerlin1 = textscan(fid,'%s %f%s %s %f%s %s %s',1,'Delimiter','delim');
fclose(fid); % close file
Any help regarding the problem are really appreciated.

Accepted Answer

Cris LaPierre
Cris LaPierre on 2 Sep 2020
Think of fid as a pointer that tells textscan where to read from. It moves its way byte by byte through the file until it reaches the end. When you call textscan for Headerlin1, it's at the end of the file. Your option, then, is to either read in Headerlin1 first, and then continue with reading in the rest of the file, or use frewind to bring fid back to the beginning of the file before reading in the first line.
You can get textscan to skip the text before a number by placing that text right before the format spec: Lat:%f
Option 1
fid=fopen('aa__file002.txt');
Headerlin1 = textscan(fid,'Lat:%f Lon:%f %*[^\n]','Delimiter',','); % extra bit reads to the end of the line
A = textscan(fid,'%s %s %f','HeaderLines',5); % read file;
fclose(fid);
Option 2
fid=fopen('aa__file002.txt');
A = textscan(fid,'%s %s %f','HeaderLines',6); % read file;
frewind(fid);
Headerlin1 = textscan(fid,'Lat:%f Lon:%f','Delimiter',',');
fclose(fid);
  2 Comments
Cris LaPierre
Cris LaPierre on 2 Sep 2020
Edited: Cris LaPierre on 6 Sep 2020
For easier handling of dates and time, consider reading in the date as a datetime, and the time as a duration.
A = textscan(fid,'%{dd-MMM-yyyy}D %{hh:mm:ss}T %f','HeaderLines',5); % read file;
Read more about these datatypes here.
hanif hamden
hanif hamden on 5 Sep 2020
Thank you very much and also thanks for sharing the information

Sign in to comment.

More Answers (0)

Categories

Find more on Large Files and Big Data in Help Center and File Exchange

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!