Find Second Closest Datetime

9 次查看(过去 30 天)
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!

采纳的回答

Adam Danz
Adam Danz 2020-2-14
编辑:Adam Danz 2020-2-17
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 个评论
Curious Mind
Curious Mind 2020-2-17
Thank you @Adam Danz for your patience and guidance. This is absolutely nice of you!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Dates and Time 的更多信息

标签

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by