How to use textscan for multiple variables

4 views (last 30 days)
Hello,
I am currently working on a project where i import a gpxfile without gpxread, and sort the data into variables (elevation, longitude, etc.).
However, my code keeps bringing up empty matrixes for my variables.
Any help would be appreciated!
filename = input('Open file: ', 's');
[fileID, errmsg]= fopen(filename);
if (fileID==-1)
disp(errmsg)
end
a=importdata(filename);
d=char(a)
~feof(fileID)
Latitude = textscan(d,'<trkpt lat="%f" lon="%f">\n');
for Longitude = textscan(d, 'long="%f">\n');
for Elevation = textscan(d, '<ele>%f</ele>)\n');
for Time = textscan (d, '<time>2020-02-01T%f3z</time>\n');
end
end
end
fgetl(chr);

Accepted Answer

Walter Roberson
Walter Roberson on 15 Oct 2022
a=importdata(filename);
d=char(a)
Okay, so d is a character vector or character array -- in particular, d is not a file id. You did [fileID, errmsg]= fopen(filename); but you never use the fileID other than to check feof() once on it and discard the results of the check.
Latitude = textscan(d,'<trkpt lat="%f" lon="%f">\n');
You are passing the characters in d to textscan. It is valid for textscan purposes if d is a 2D array of characters: textscan will take the characters in linear index order in such a case (which would read along columns, not across rows).
textscan() will skip leading whitespace in most cases, and then will try to literally match what is in d against '<' 't' 'r' k' 'p' 't' and so on in consecutive positions. If the first non-whitespace does not match the literal characters <trkpt lat=" then textscan() will stop reading and return empty. textscan() never searches through the text looking for matching places: it always starts at the current position and tries to match the next format item. The current position for a character array is the beginning of the array.
for Longitude = textscan(d, 'long="%f">\n');
Reminder that when textscan() works, it returns a cell array of values. If textscan() were able to find multiple occurances of that pattern in a row, with there being only one % format, it would return a cell array that contained a single entry, and the single entry would be a numeric column vector.
You would be on better grounds if you were reading from a file instead of from a character array, but you would be much better off using something like regexp() to parse the text.
Given the structure of the file, possibly you could use xmlread() or readstruct()

More Answers (0)

Tags

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!