Find Second Closest Datetime
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Adam Danz
le 14 Fév 2020
Modifié(e) : Adam Danz
le 17 Fév 2020
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 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Calendar dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!