Trouble finding the closest match in a datetime array given a datetime value.

7 visualizaciones (últimos 30 días)
Hi, so I have two datetime arrays timeForce and timePos. I am trying to loop through timePos and find the closest match to each value in the timeForce array. Below is the function I am using to find the closest match. This should work to find the closest match but it keeps selecting the last index of the timeForce array for every value of timePos. I'm not really sure why this is happening and would really appreciate some help with this. Thank you so much!
function closestTime = findClosestDatetime(datetimeArray, singleDatetime)
% This updated version assumes datetimeArray and singleDatetime might be strings or datetime objects.
% Define the expected datetime format
datetimeFormat = 'HH:mm:ss.SSS';
% Ensure datetimeArray is in the correct format
if isstring(datetimeArray) || iscellstr(datetimeArray) || ischar(datetimeArray)
datetimeArray = datetime(datetimeArray, 'InputFormat', datetimeFormat);
end
% Ensure singleDatetime is in the correct format
if isstring(singleDatetime) || ischar(singleDatetime)
singleDatetime = datetime(singleDatetime, 'InputFormat', datetimeFormat);
end
% Calculate the absolute time differences
timeDifferences = abs(datetimeArray - singleDatetime);
% Find the index of the minimum difference
[~, idx] = min(timeDifferences);
% Return the closest datetime from the array
closestTime = (idx);
end

Respuestas (1)

Voss
Voss el 1 de Abr. de 2024
Editada: Voss el 1 de Abr. de 2024
timePos = load('timePos').timePos;
timeForce = load('timeForce').timeForce;
The elements of timeForce all represent date/times in the year 1899 (specifically December 31, 1899). One way to see that is to change the Format of timeForce to include a date, e.g.:
timeForce.Format = 'yyyy/MM/dd HH:mm:ss.SSS';
timeForce([1 end])
ans = 2x1 datetime array
1899/12/31 13:28:44.911 1899/12/31 13:30:54.912
The elements of timePos all represent date/times from April 1, 2024, so the nearest timeForce is always the latest one (which is the last one in this case).
If the elements of timeForce should not be from 1899, then check the code that creates timeForce and fix it so that timeForce has the correct dates, or if you cannot change that code, you can add an appropriate offset (i.e., an integer number of days) to timeForce to make them accurate, e.g., to make them date/times from April 1, 2024:
timeForce = timeForce + calyears(124) + calmonths(3) + caldays(1);

Categorías

Más información sobre Dates and Time en Help Center y File Exchange.

Productos


Versión

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by