MATLAB: Extract a variable from middle of a line of a .dat file with mixed text and numbers

extract variableMATLAB

Hello.
I'm a fairly new user of MatLab and I'm having some difficulty reading data from a .dat file.I want to extract specific values from a line of the file I'm using. That line has both text and the values i want. From the sample I'm posting bellow I want to extract the values of LAT i.e. 50 55.51 and LONG i.e. -40 26.26. I would like to get 50 55.51 -40 26.26 as different variables so I can use them to convert to decimal coordinates 50.93 and -40.44, using something like this:
lat_deg = 50 % extract from file.dat



lat_min = 55.51 % extract from file.dat
lon_deg = -40 % extract from file.dat
lon_min = 26.26 % extract from file.dat
lat = lat_deg+lat_min/60
lon = lon_deg+long_min/60
_________________sample____________________________
STATION 2 DATE 1 27 1999 TIME 14:57 TO 17:08
LAT 50 55.51 LONG -40 26.26 WATER DEPTH 4060 M
PRESS TEMP SALINITY RHO(T,S,P)
(M) (C) (PSS-78) (KG M-3)
2. 18.623 35.658 1025.35
5. 18.627 35.657 1025.56
10. 18.623 35.658 1025.79
The computers I use run Matlab R2008a, but sometimes I'll need to use the older Matlab 6.5 version. Any help is appreciated.
edited: to correct LAT/LONG values and indicate Matlab versions I'll be using

Best Answer

If LAT/LONG can really be anywhere in the file (not on 2nd line as shown in your sample), you could go for a regexp solution:
>> buf = fileread('myData.dat') ;
>> pat = 'LAT\s+(-?[\d\.])+\s+(-?[\d\.]+)\s+LONG\s+(-?[\d\.]+)\s+(-?[\d\.]+)' ;
>> tokens = regexp(buf, pat, 'tokens') ;
>> lat = str2double(tokens{1}(1:2))
lat =
50.0000 55.5100
>> long = str2double(tokens{1}(3:4))
long =
-40.0000 26.2600
There are thousands of ways to implement this with REGEXP; here is another possibility:
>> buf = fileread('myData.dat') ;
>> match = regexp(buf, '(?<=LAT\s+)-?[\d\.]+\s+-?[\d\.]+', 'match') ;
>> lat = str2num(match{1})
lat =
50.0000 55.5100
>> match = regexp(buf, '(?<=LONG\s+)-?[\d\.]+\s+-?[\d\.]+', 'match') ;
>> long = str2num(match{1})
long =
-40.0000 26.2600
Let me know if you want more information about how we are using REGEXP here.