compare datetime with different lengths
2 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
回答(2 个)
Ameer Hamza
2020-11-16
编辑:Ameer Hamza
2020-11-16
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 个评论
Ameer Hamza
2020-11-17
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);
Peter Perkins
2020-11-19
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Categorical Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!