我已经编写了一些matlab代码但是我遇到了问题,因为它没有给出所需的答案..
当我跑步时
track = readTrack('test1.gpx');
disp(track);
我以
的形式得到答案1x4 struct array containing the fields:
name
points
但理想情况下,我应该得到像
这样的测试包含字段的标量结构:
name = Test #1
points =
0.00000 0.00000 0.00000
0.00000 2.00000 2.10000
0.00000 7.00000 4.50000
0.00000 10.00000 10.00000
有关如何更改代码以执行此操作以及如何更改的任何建议?
谢谢! :)
这是我的代码。
function data = readTrack(filename)
%creates a struct with fields 'name' and 'points' from data extracted
%from gpx file. it uses supporting functions.
fid=fopen(filename);
if fid == -1
result = error (filename);
else
[data,name,point] = setUp(fid);
while length(point) > 9
[pointStruct, point] = findLatLongElev(point,fid,name);
data = [data pointStruct];
end
end
end
function result = error(filename)
% displays error message and produces empty struct
sprintf('File ''%s'' not found.',filename);
result = struct();
end
function [data,name,point] = setUp(fid)
%set up function, finds the name and gets to right place to find the
%points
data=[];
lineSkip(3,fid);
name = findNameOrElevation(fid);
lineSkip(13, fid);
point = fgetl(fid);
end
function lineSkip(n, fid)
%skips lines
for i=1:n
fgetl(fid);
end
end
function result = findNameOrElevation(fid)
% finds the name, however also used to find elevation as data presented
% in similar formats
line = fgetl(fid);
findStart = strfind(line,'>');
findFinish = strfind(line,'<');
printStart = findStart(1)+1;
printFinish = findFinish(2)-1;
result = line(printStart:printFinish);
end
function [pointStruct, point] = findLatLongElev(point,fid,name)
% finds latitude, longitude and elevation and creates a struct field
% entry for each set of points
apostrophes = strfind(point, '"');
latStart = apostrophes(1)+1;
latFinish = apostrophes(2)-1;
longStart = apostrophes(3)+1;
longFinish = apostrophes(4)-1;
trackPoint(1) = str2double(point(latStart:latFinish));
trackPoint(2) = str2double(point(longStart:longFinish));
trackPoint(3)= str2double(findNameOrElevation (fid));
fgetl(fid);
point = fgetl(fid);
pointStruct = struct(...
'name',name,...
'points', trackPoint);
end
答案 0 :(得分:0)
我希望我能在这里得到标量结构和stuct数组之间的关系。猜测是标量字段中的一行应该对应于来自结构数组的相同字段中的一个元素。如果我是正确的,可以编辑这个问题以使其更清楚。所以答案,
在函数readTrack
中,您实际上明确声明您想要一个结构数组。
while length(point) > 9
[pointStruct, point] = findLatLongElev(point,fid,name);
data = [data pointStruct]; % <--Here! Adds another element to an array of structs.
end
要使用标量结构,您可以改为使用每个元素。
while length(point) > 9
[pointStruct, point] = findLatLongElev(point,fid,name);
data.name = [data.name; mat2cell(pointStruct.name,1,length(pointStruct.name))];
data.point = [data.point; pointStruct.point];
end
但是,您需要将名称转换为单元格,因为字符串不一定具有相同的长度,并且在大多数情况下*不应该假设这样。这也需要在setUp
data={};
但是,我想,如果你在一个单独的函数中继续保持当前输出链接字段,那么代码将更具可读性。可以使用vertcat
为每个字段执行此操作。但是,除非所有字符串长度相同或字段data.name为单元格,否则仍会出现“矩阵维度不一致”错误。这可以通过循环完成,因为字段名称可以从函数fieldnames
获得。
*如果字符串用于表示其他内容,则可能是例外,例如。 8个字符可用于表示64位整数。