It’s the second time since I have been using MATLAB that I need to find the closest date to a given target date in an array. Of course I didn’t remember how I did it the last time and I couldn’t find a solution that suited my needs on the internet. So I decided to document it for myself and everyone else who is interested.
- a list (represented as a cell array in MATLAB) of dates
- a date
- a variable that contains the pattern of the date date_str_pattern
- to find the date in my cell array, that’s closest to my given target date
- to provide my function with a parameter ‘before’, ‘after’, or ‘any’, to indicate whether I want the closest date that was before or after my target date or I don’t care whether it was before or after
I’m really not a fan of how MATLAB handles dates but the datenum() function is well suited for this task. By passing a date string and the pattern which I store in date_str_pattern, we can convert the date to a numeric value and use it for computations and comparisons (like greater, smaller, …).
Solution & code
With the power of datenum(), this task was actually not difficult anymore. In a first step, we use the method to convert the cell array dates and the date target_date to datenums. Then we subtract the target date from all dates, to get positive and negative difference between the dates.
Then it’s just a matter of finding the index of the minimum (case: “after”) or maximum (base: “before”) that is larger/smaller than 0. In case we just want the closest that, no matter if it’s before or after our target date, we only the need the index of the minimum absolute difference.
The exact code can be found in get_closest_date.m.
My test cases can be found in get_closest_date_test.m.
Feel free to leave a comment if this helped you or you have any suggestions!