For loop not doing what I want it to

1 次查看(过去 30 天)
% Create counter for indexing of new table.
counter = 1;
% Create empty table for x coordinates
sampled_x_coord = [];
sampled_x_coord_table = array2table(sampled_x_coord);
% Create empty table for y coordinates.
sampled_y_coord = [];
sampled_y_coord_table = array2table(sampled_y_coord);
% Create ignore next variable, assign to false for start of loop.
ignore_next = false;
for i = 1:height(path_data)
if ignore_next == true
ignore_next = false;
elseif ignore_next == false
if path_data.time(i) == path_data.time(i + 1)
sampled_x_coord_table.sampled_x_coord(counter) = ((path_data.x(i) + path_data.x(i + 1)) / 2);
sampled_y_coord_table.sampled_y_coord(counter) = ((path_data.y(i) + path_data.y(i + 1)) / 2);
ignore_next = true;
counter = counter + 1;
elseif path_data.time(i) ~= path_data.time(i + 1)
sampled_x_coord_table.sampled_x_coord(counter) = path_data.x(i);
sampled_y_coord_table.sampled_y_coord(counter) = path_data.y(i);
ignore_next = false;
counter = counter + 1;
end
end
end
See my for loop above, what I am doing is going through and comapring a time variable in one row to the time variable in the next row. If the time variables are the same, then I'm averaging two x and y coordinate values and using that as my x and y coordinate value. If they are the same, then I want to skip the next row in the table, which is what I do with the ignore_next variable.
If the time variables are different, then I just want to take the x and y coordinate for that row and use that (without any averaging) as my data points.
The for loop works for the first scenario, averaging the two x and y coordinates if the time variables are the same, but if the time variables are differernt, then it creates an empty row in the sampled_x_coord_table and sampled_y_coord_table tables.

采纳的回答

dpb
dpb 2021-6-7
编辑:dpb 2021-6-7
TT=table2timetable(path_data); % convert the table to a time table
TT=retime(TT,unique(TT.time),'mean'); % retime to included times, average identical times
See documentation for timtetable and retime for details, other options...

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by