matlabsearchtimetable

Retrieve matlab timetable points next to specific timedata


I've the following timetable in Matlab:

intersectionPoints =

  10×1 timetable

         Timestamp          Value 
    ____________________    ______

    01-Feb-2016 00:00:00    1.0848
    01-Feb-2016 01:00:00    1.0847
    01-Feb-2016 04:00:00    1.0848
    02-Feb-2016 14:07:44    1.0914
    02-Feb-2016 17:21:36    1.0916
    03-Feb-2016 01:49:18    1.0917
    03-Feb-2016 07:18:43    1.0919
    04-Feb-2016 00:53:20    1.1088
    04-Feb-2016 04:18:16    1.1097
    04-Feb-2016 21:38:10    1.1199

I've also the following timedate:

checkDate = datetime("03-Feb-2016 01:49:20")

checkDate = 

  datetime

   03-Feb-2016 01:49:20

I want to retrieve from intersectionPoints timetable the rows that are the previous one and the next one to specific timestamp. In my specific case I need to retrieve thosw two points:

res =

  2×1 timetable

         Timestamp          Value 
    ____________________    ______

    03-Feb-2016 01:49:18    1.0917
    03-Feb-2016 07:18:43    1.0919

res is a timetable with two elements. These are the two nearest point of intersectionPoints to checkDate, in the past and in the future related to checkDate. I can loop over all timestamp value and check them manually, but it's not efficient (my timetables are big). I can also perform a manual binary search to those elements, but I'd like to know if there's a built-in or more simple way to search for those two values.

How can I find timetable values that are next to a defined one?


Solution

  • The cool thing about MATLAB is that it was created for engineers and it is supposed to work as non-informatics expect. So simply find the first (find(...,1)) element which is > than your checkDate:

    time = [datetime('yesterday')
            datetime('today')
            datetime('tomorrow')];
    checkDate = datetime('now');
    Tbl = timetable(time,(1:length(time)).');
    
    idx = find(Tbl.time > checkDate ,1);
    
    res = Tbl(idx-1:idx,:)