MATLAB Answers

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

2 views (last 30 days)
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

Accepted Answer

the cyclist
the cyclist on 22 Jul 2021
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 Comment
Louise Wilson
Louise Wilson on 22 Jul 2021
Thank you! This makes perfect sense. I usually comment but forgot to here somehow, I will try to be more vigilant! Thank you

Sign in to comment.

More Answers (0)

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by