Pairwise difference of datetime vectors (i.e. pdist for time data)
2 次查看(过去 30 天)
显示 更早的评论
I have two datetime vectors of differing lengths (500x1 and 15000x1) and was wondering how to produce a 500x15000 matrix of the differences between these times. I've previously used pdist2() to answer this question for double vectors, but can't find the function to do it for datetimes.
0 个评论
采纳的回答
Peter Perkins
2019-7-2
编辑:Peter Perkins
2019-7-2
pdist is probably much more than you actually need, assuming that by "distance" you mean a simple subtraction. pdist is designed for pairwise diatances between vectors, using one of several distance measures. It will do what you want, but is kind of overkill. I think what you are looking for is what's referred to as "implicit expansion", a more elegant behavior that addresses the same cases as bsxfun used to be used for:
>> (1:3) - (1:4)'
ans =
0 1 2
-1 0 1
-2 -1 0
-3 -2 -1
I forget when this was added; a few years ago IIRC. In any case, you are right that datetime does not yet support it. But it's easy to do by hand, using ndgrid:
>> d1 = datetime(2019,7,1,0:4,0,0);
>> d2 = datetime(2019,7,1,0:3,0,30);
>> [D1,D2] = ndgrid(d1,d2)
D1 =
5×4 datetime array
01-Jul-2019 00:00:00 01-Jul-2019 00:00:00 01-Jul-2019 00:00:00 01-Jul-2019 00:00:00
01-Jul-2019 01:00:00 01-Jul-2019 01:00:00 01-Jul-2019 01:00:00 01-Jul-2019 01:00:00
01-Jul-2019 02:00:00 01-Jul-2019 02:00:00 01-Jul-2019 02:00:00 01-Jul-2019 02:00:00
01-Jul-2019 03:00:00 01-Jul-2019 03:00:00 01-Jul-2019 03:00:00 01-Jul-2019 03:00:00
01-Jul-2019 04:00:00 01-Jul-2019 04:00:00 01-Jul-2019 04:00:00 01-Jul-2019 04:00:00
D2 =
5×4 datetime array
01-Jul-2019 00:00:30 01-Jul-2019 01:00:30 01-Jul-2019 02:00:30 01-Jul-2019 03:00:30
01-Jul-2019 00:00:30 01-Jul-2019 01:00:30 01-Jul-2019 02:00:30 01-Jul-2019 03:00:30
01-Jul-2019 00:00:30 01-Jul-2019 01:00:30 01-Jul-2019 02:00:30 01-Jul-2019 03:00:30
01-Jul-2019 00:00:30 01-Jul-2019 01:00:30 01-Jul-2019 02:00:30 01-Jul-2019 03:00:30
01-Jul-2019 00:00:30 01-Jul-2019 01:00:30 01-Jul-2019 02:00:30 01-Jul-2019 03:00:30
>> delta = D1 - D2
delta =
5×4 duration array
-00:00:30 -01:00:30 -02:00:30 -03:00:30
00:59:30 -00:00:30 -01:00:30 -02:00:30
01:59:30 00:59:30 -00:00:30 -01:00:30
02:59:30 01:59:30 00:59:30 -00:00:30
03:59:30 02:59:30 01:59:30 00:59:30
That makes two temporary arrays as big as the result, but however you do this, you will end up with a 15000x500 array as your result (unless I've misunderstood).
1 个评论
dpb
2019-7-3
Good point, Peter! I didn't really think about the calculation itself as just thinking of how to get around the input data type mismatch for OP...
更多回答(1 个)
dpb
2019-7-2
Presuming not excessive precision, one could convert to datenum, compute distances and then return to datetime
Seems like a feature enhancement.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!