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



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

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

除了@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来提取时间分量,使用hours来创建duration实例。

这里有一种方法,可以在显式删除除时间信息之外的所有内容后选择行。设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,:);

最新更新