MATLAB Answers

Find Second Closest Datetime

20 views (last 30 days)
Curious Mind
Curious Mind on 14 Feb 2020
Commented: Adam Danz on 17 Feb 2020
Hi all,
I have two datetime tables say A and B. I am able to compare A to B and extract the datetimes in A nearest to B with no repetitions. That’s no datetime in A can be selected twice.
Now I want to compare A to B and instead of the nearest in A to B, I want to select or find the second nearest or highest datetime. For example, given the following datetimes, A = 2/1/2016 11:42, 2/1/2016 11:44 and B = 2/1/2016 11:43. The closest datetime comparing A to 2/1/2016 11:43 in B is 2/1/2016 11:42. Now what if I want to select the second highest or second closest/nearest datetime to 2/1/2016 11:43? In this case it will be 2/1/2016 11:44. I want to do this in a loop since A and B contains multiple datetimes. Compare A to B and select the indexes of all second nearest/highest/closest datetime in A to B. And then I will use the indexes to extract row data from another table. I am still learning and I appreciate your help. Thanks!

  0 Comments

Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 14 Feb 2020
Edited: Adam Danz on 17 Feb 2020
This is a slight modification from the answer in your previous question.
It uses [B,I] = mink(A,k) to locate the k_th smallest value in array A.
See two lines with the comment " % CHANGED " and one line with the comment " % ADDED " to see how this answer differs from the previous one.
Also note that this can be used instead of the previous one by setting nThClosest to 1.
% Create two arrays of random dates (may contain repeated dates)
dates1 = datetime(2019,1,1)+days(sort(randi(364,1,100)));
dates2 = datetime(2018,12,28)+days(sort(randi(364,1,100)));
% Select the n_th closest date (positive integer)
nThClosest = 2; % ADDED
% Loop through the dates in date1
nearestIdx = nan(size(dates1)); % Pre allocation
dates2Temp = dates2; % Make a temp copy of dates2 for NaT replacement
for i = 1:numel(dates1)
[~, minKdurr] = mink(abs(dates2Temp - dates1(i)),nThClosest ); % CHANGED
nearestIdx(i) = minKdurr(end); % CHANGED
dates2Temp(nearestIdx(i)) = NaT; % replace that date with NaT
end
% Sanity check: all of the values in nearestIdx should be unique
assert(numel(unique(nearestIdx))==numel(dates1),'Sanity check failure: unique date matching error.')
% Match the dates (dates1 and dates2 must have same size)
m = [dates1.', dates2(nearestIdx).']

  2 Comments

Curious Mind
Curious Mind on 17 Feb 2020
Thank you @Adam Danz for your patience and guidance. This is absolutely nice of you!
Adam Danz
Adam Danz on 17 Feb 2020
Glad I can help!

Sign in to comment.

More Answers (0)

Tags

Products


Release

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!