# difference of datetimes using the "diff" function

3 views (last 30 days)
Sim on 20 Oct 2022
Commented: Sim on 21 Oct 2022
I would like to find the temporal difference between the elements in the first (left) column and the elements in the second (right) column. I have tried the diff function, but it gives me an unexpected result. How can I still use the diff function correctly ?
% input
a = datetime({'2022-05-17 05:57:11.568' '2022-05-17 06:01:23.552'
'2022-05-17 06:01:23.552' '2022-05-17 06:02:32.760'
'2022-05-17 06:02:32.760' '2022-05-17 06:03:57.660'
'2022-05-17 06:03:57.660' '2022-05-17 06:19:28.740'
'2022-05-17 06:19:28.740' '2022-05-17 06:20:50.100'
'2022-05-17 06:20:50.100' '2022-05-17 06:21:49.408'
'2022-05-17 06:21:49.408' '2022-05-17 06:23:15.980'
'2022-05-17 06:23:15.980' '2022-05-17 06:24:22.200'})
a = 8×2 datetime array
17-May-2022 05:57:11 17-May-2022 06:01:23 17-May-2022 06:01:23 17-May-2022 06:02:32 17-May-2022 06:02:32 17-May-2022 06:03:57 17-May-2022 06:03:57 17-May-2022 06:19:28 17-May-2022 06:19:28 17-May-2022 06:20:50 17-May-2022 06:20:50 17-May-2022 06:21:49 17-May-2022 06:21:49 17-May-2022 06:23:15 17-May-2022 06:23:15 17-May-2022 06:24:22
% If I use "diff(a)", why do I get two columns of "differences", instead of only one ?
diff(a)
ans = 7×2 duration array
00:04:11 00:01:09 00:01:09 00:01:24 00:01:24 00:15:31 00:15:31 00:01:21 00:01:21 00:00:59 00:00:59 00:01:26 00:01:26 00:01:06
% the following command looks like to give the correct result (but I would like to use "diff" if possible)
abs(a(:,1)-a(:,2))
ans = 8×1 duration array
00:04:11 00:01:09 00:01:24 00:15:31 00:01:21 00:00:59 00:01:26 00:01:06
##### 2 CommentsShowHide 1 older comment
Sim on 21 Oct 2022
ah ok, thanks a lot for your explanation! :-)

Sim on 20 Oct 2022
ah.... probably this one ?
>> diff(a,1,2)
ans =
8×1 duration array
00:04:11
00:01:09
00:01:24
00:15:31
00:01:21
00:00:59
00:01:26
00:01:06