compare datetime with different lengths

10 views (last 30 days)
SW
SW on 16 Nov 2020
Answered: Peter Perkins on 19 Nov 2020
I have two datetime variables: dt_D and dt_C. They cover the same set of time but dt_C is significantly shorter becuase it is missing timesteps.
I would like to plot two other variables, D & C, (which are the same length as their respective datetimes) when they both have data at the same timestep. I do not want to do any interpolation, just simply plot the variables when they overlap. Another alternative would be to remove timesteps from dt_D when they do not exist in dt_C.
Is there an easy way to do this?

Answers (2)

Ameer Hamza
Ameer Hamza on 16 Nov 2020
Edited: Ameer Hamza on 16 Nov 2020
There can be several ways to do this. For example, see interp1() or retime().
This code shows an example
t1 = datetime(2020,1,1):datetime(2020,1,20);
y1 = rand(size(t1));
t2 = datetime(2020,1,1):days(4):datetime(2020,1,20);
y2 = rand(size(t2));
y2_t1 = interp1(t2, y2, t1, 'linear', 'extrap');
figure()
axes();
hold on;
plot(t1, y1);
plot(t1, y2_t1);
  2 Comments
SW
SW on 16 Nov 2020
Thanks for your response. I do not want to do any interpolation though, rather I would just like to isolate the variables when they have overlapping timesteps.
Ameer Hamza
Ameer Hamza on 17 Nov 2020
If you just want common elements then you can try intersect()
t1 = datetime(2020,1,1):datetime(2020,1,20);
y1 = rand(size(t1));
t2 = datetime(2020,1,1):days(4):datetime(2020,1,20);
y2 = rand(size(t2));
[t_new, idx1, idx2] = intersect(t1, t2);
y1_new = y1(idx1);
y2_new = y2(idx2);
figure()
axes();
hold on;
plot(t_new, y1_new);
plot(t_new, y2_new);

Sign in to comment.


Peter Perkins
Peter Perkins on 19 Nov 2020
SW, if all you want is a plot, there's nothing special you need to do, just plot them.
t1 = datetime(2020,11,19) + caldays(0:2:10)';
y1 = rand(size(t1));
t2 = datetime(2020,11,17) + caldays(0:15)';
y2 = rand(size(t2));
plot(t1,y1,'-o');
hold on;
plot(t2,y2,'-x');
hold off
If you really do want to up/downsample, put them in a timetable and use synchronize. It's a one-liner, and very easy to do other similar things like interpolation or whatever.
>> tt1 = timetable(t1,y1);
>> tt2 = timetable(t2,y2);
>> tt12 = synchronize(tt1,tt2,'intersect')
tt12 =
6×2 timetable
t1 y1 y2
___________ ________ ________
19-Nov-2020 0.13612 0.012766
21-Nov-2020 0.79886 0.92698
23-Nov-2020 0.007788 0.78629
25-Nov-2020 0.85174 0.31578
27-Nov-2020 0.10331 0.053424
29-Nov-2020 0.5331 0.59552

Categories

Find more on Categorical Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!