MATLAB: How to select a time from one array which is close to the time in another array

time

I have 2 time arrays (input)
A = [{'05:10:34'} {'05:42:52'} {'06:52:17'} {'07:34:36'} {'07:44:37'} {'08:44:35'}]
B = [{'05:07:46'} {'05:14:43'} {'05:18:25'} {'05:40:04'} {'05:46:02'} {'06:00:32'} {'06:29:36'} {'06:49:31'} {'07:31:48'} {'07:41:49'} {'07:47:48'}]
need to select time of B which is closest to time in A (but time difference between A and B should not be more than 15 min).
and the time in B that has least time difference from A should be the desired output as below:
c = [{'05:07:46'} {'05:40:04'} {'06:49:31'} {'07:31:48'} {'07:41:49'}]

Best Answer

Prefer to use modern datetime objects instead of cellstrings containing datestr values:
A = [{'05:10:34'} {'05:42:52'} {'06:52:17'} {'07:34:36'} {'07:44:37'} {'08:44:35'}];
B = [{'05:07:46'} {'05:14:43'} {'05:18:25'} {'05:40:04'} {'05:46:02'} {'06:00:32'}, ...
{'06:29:36'} {'06:49:31'} {'07:31:48'} {'07:41:49'} {'07:47:48'}];
a = datetime(A);
b = datetime(B);
c = NaT(size(a));
for k = 1:numel(A)
[dist, index] = min(abs(a(k) - b));
if minutes(dist) < 15
c(k) = b(index);
end
end
If you really need the olde datestr elements:
a = datenum(A);
b = datenum(B);
c = cell(size(a));
for k = 1:numel(A)
[dist, index] = min(abs(a(k) - b));
if dist < 1 / 96 % Explicitly: 15*60/86400
c{k} = B{index};
end
end