How to use textscan for multiple variables
7 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Sarah
el 15 de Oct. de 2022
Respondida: Walter Roberson
el 15 de Oct. de 2022
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);
0 comentarios
Respuesta aceptada
Walter Roberson
el 15 de Oct. de 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()
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!