MATLAB: Pairwise difference of datetime vectors (i.e. pdist for time data)

datetimedifferencedistanceMATLABpairwisepdisttime

I have two datetime vectors of differing lengths (500×1 and 15000×1) and was wondering how to produce a 500×15000 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.

Best Answer

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).