# Indexing different time ranges from a Timetable.

72 views (last 30 days)
John Gagnon on 17 Apr 2019
Commented: Adam Danz on 18 Jan 2021
So i am playing around with timetable data. The Data im working with has Both Date and TIme (in 12hr format)
I want to be able to index a couple differnt time frames.
First is I want to select all times from 11am to 12pm irrespective of the date. (when I set a time range with no date matlab just adds todays date.)
Second is I want to select all times from 11am to 12pm through a range of months say Jan-Mar

Adam Danz on 17 Apr 2019
"First is I want to select all times from 11am to 12pm irrespective of the date. "
% Make fake data
MeasurementTime = (datetime('2018-12-01 01:00') : 0.05 : datetime('2019-04-01 11:30 PM'))';
Temperature = randi(100, size(MeasurementTime));
TT = timetable(MeasurementTime,Temperature);
% Extract hour of day (24 hr format)
hourOfDay = hour(TT.MeasurementTime);
% Determine which time stamps are between 11am and 12pm
b = [11, 12]; %[start, end] of desired time bounds (24 hr format)
selectedTimes = hourOfDay >= b(1) & hourOfDay <= b(2);
% isolate all rows of timetable between desired time bounds
TT(selectedTimes,:)
"Second is I want to select all times from 11am to 12pm through a range of months say Jan-Mar"
% Extract hour of day (24 hr format)
hourOfDay = hour(TT.MeasurementTime);
% Extract month number
monthNum = month(TT.MeasurementTime);
% Determine which time stamps are between 11am and 12pm for january to march
b = [11, 12]; %[start, end] of desired time bounds (24 hr format)
m = [1, 3]; %[start, end] of desired month bounds
selectedTimes = hourOfDay >= b(1) & hourOfDay <= b(2);
selectedMonths = monthNum >= m(1) & monthNum <= m(2);
% isolate all rows of timetable between desired time and month bounds
TT(selectedTimes & selectedMonths,:)
Adam Danz on 18 Jan 2021
> is there a way to put the results back to your entire year in their own location?
Yes. You use the same indexing you used to pull the tables apart in the first place. But if you're just multiplying by 10, you don't need to break apart the table. You can just do,
% continuing from the first example in my answer
TT.Temperature(selectedTimes) = TT.Temperature(selectedTimes) * 10;
% Or
% continuing from the second example in my answer
idx = selectedTimes & selectedMonths;
TT.Temperature(idx) = TT.Temperature(idx) * 10;

R2016b

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!