Search code examples
matlabtimetable

Define timerange in Matlab simply based on time (not date)


I am trying to use the Matlab timerange function to select rows of a timetable within a specific time interval, e.g. between 12:00:00 and 16:00:00. Because I have 30 different days, each day covering various timings, I would like to ignore the date and retrieve all the rows whose times fall within my time interval, irrespective of the day. If I only write the time in the line below, Matlab uses today by default. I would be very grateful if someone could help me finding out how to only use time (and not dates) as an index.

S = timerange('??? 12:00:00','??? 16:00:00');
Output = TT(S,:);

Solution

  • Further to @aksadv's answer, there's a slightly neater solution using duration types, like so:

    times = datetime(2017, 01, randi([1 31], 10, 1), ...
        randi(24, 10, 1), randi(60, 10, 1), randi(60, 10, 1));
    tt = timetable(times, rand(10, 1));
    % Use TIMEOFDAY to convert datetimes into durations representing
    % the time of day:
    tt.times = timeofday(tt.times)
    % TIMERANGE can be used with durations too. Use HOURS to construct
    % the duration objects
    tt(timerange(hours(12), hours(16)), :)
    

    This uses timeofday to extract the time component, and hours to create duration instances.