简单地根据时间(不是日期)在 Matlab 中定义时间范围

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

我正在尝试使用 Matlab timerange 函数在特定时间间隔内 select 行时间表,例如在 12:00:00 和 16:00:00 之间。因为我有 30 天不同的日子,每一天都有不同的时间,所以我想忽略日期并检索所有时间在我的时间间隔内的行,而不管那一天。如果我只在下面一行写时间,Matlab 默认使用今天。如果有人能帮我找出如何只使用时间(而不是日期)作为索引,我将不胜感激。

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

这是一种在显式删除除时间信息以外的所有内容后选择行的方法。设 TT 为输入时间表。

% Create another timetable with the same time information
%  It also has one data column which represents the row index
tempTT = timetable(TT.Time, (1:height(TT))');

% remove the Year, Month, and Date information
tempTT.Time.Year  = 1;
tempTT.Time.Month = 1;
tempTT.Time.Day   = 1;

% Select the desired timerange
S = timerange('1-1-1 12:00:00','1-1-1 16:00:00');

% Get the row indices of the selected rows
idxSel = tempTT(S,:).Variables;

% Select the desired rows from the original timetable
Output = TT(idxSel,:);

除了@aksadv 的回答之外,还有一个使用 duration 类型的稍微简洁的解决方案,如下所示:

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)), :)

这使用 timeofday to extract the time component, and hours 创建 duration 个实例。