MATLAB: Printing matching lines of text from a text file

matching texttext file

And what is it supposed to be?

Best Answer

This looks like a bad approach. If your input file uses a 3-digit degree, then all your values are ruined.
lat_deg = str2double(l(1:2));
lat_min = str2double(l(4:5));
long_deg = str2double(l(8:9)); %WHAT IF it's a 3-digit degree?
long_min = str2double(l(11:12));
For instance:
72°47N 56°09W Upernavik Greenland Denmark
71°39N 128°52E Tiksi Sakha Republic Russia
1234567890123456789
-- -- -- --
For Russia, str2double(l(8:9)) will NOT get "128".
Here are some pointers. Not sure what you need:
%Consider reading all the file text at once, if it's not too large. This prevent your program from accumulating too many open files (fopen + error leaves a lot of open files).
FID = fopen('cities.txt', 'r');
HDR = regexp(fgetl(FID), '\t', 'split');
FMT = repmat('%s', 1, numel(HDR));
TXT = textscan(FID, FMT, 'delimiter', '\t');
fclose(FID);
Data = [TXT{:}];
%Use sscanf to get the degree, minutes, and NSEW direction
DegMinDir = sscanf(Data{1, 1}, '%d°%d%c');
Deg = DegMinDir(1);
Min = DegMinDir(2);
Dir = char(DegMinDir(3));
%If you want to find all Data for a particular state, use ismember or strcmpi
state = 'Aysén';
StateLoc = strcmpi(Data(:, 4), state);
StateData = Data(StateLoc, :);
%I recommend adding some protection against wrong state names inputted by the user
%such as "alabama" or "Alabama " instead of exactly "Alabama"
switch (lower(strtrim(state)))
case 'alabama'
...
otherwise
error('not a valid state name');
end
Related Question