Find Second Closest Datetime

조회 수: 9 (최근 30일)
Curious Mind
Curious Mind 2020년 2월 14일
댓글: Adam Danz 2020년 2월 17일
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!
Adam Danz
Adam Danz 2020년 2월 17일
Glad I can help!

댓글을 달려면 로그인하십시오.

추가 답변 (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