How to plot successive rows of a table when value is true

1 次查看(过去 30 天)
I have attached an example data set. What I would like to do is plot successive rows together if the time between successive rows is <2 hours. Therefore if the data is > 2 hours, we get a single point (row 1), whereas rows 2-4 would be plotted as a line because there is less than 2 hours between those successive points. I have code that works but using this method, I miss the last row of data:
subplot(5,1,1)
unique_vals=unique(gps_data.cpa3);
[ra,ca]=size(gps_sub)
for ii=1:ra-1
gps_plot(ii,:)=gps_sub(ii,:);
int=gps_sub.dt(ii+1)-gps_sub.dt(ii);
if int>hours(2)
gps_plot=rmmissing(gps_plot);
plot(gps_plot.dt,gps_plot.cpa2,'-o','LineWidth',2,'MarkerSize',1)
hold on
clear gps_plot
elseif int<hours(2)
gps_plot=[gps_plot; gps_sub(ii+1,:)];
hold on
end
end

采纳的回答

the cyclist
the cyclist 2021-7-22
This line of code
for ii=1:ra-1
is looping over all rows except for the last one, so it never "sees" the last row. Therefore, if it is more than 2 hours away from the prior row, it gets missed entirely.
You need to add logic to handle that case.
Personally, I think it might make more sense to set
gps_plot = gps_sub(1,:)
prior to the loop. Then loop over
for ii=2:ra
and if the gap is greater than 2 hours to the prior value, plot accumulated values and start over. If the gap is less than 2 hours, just accumulate.
In essence, I am saying it might be simpler to look back, than look ahead. I would also recommend commenting your code to explain the logic.
  1 个评论
Louise Wilson
Louise Wilson 2021-7-22
Thank you! This makes perfect sense. I usually comment but forgot to here somehow, I will try to be more vigilant! Thank you

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by