How do I index into a timeseries using relative datetime values
11 views (last 30 days)
Show older comments
Hi,
I have a bunch of timeseries of data from an experiment. I want to split each time series (participant data) into sections that reflect experiment intervals. I have a series of time values that represent the start of each interval, and they are imported into matlab as datetime objects which are only time values and the time values are relative to the start of the experiment i.e. 2 mins 4 seconds after the start, 4 mins 8 seconds after the start.
Conventiantly, you cannot index into a timeseries and get an interval of data using a datetime object with the 'getdatabytime' method of the timeseries. More conveniently, unlike datenum, there is no timenum method to get just the absolute number of seconds that have passed since the start of the experiment. This function would ofcourse be a nonsense without a reference datetime from which to draw the duration.
Is there a tidy and convenient way to get the necesary indexing values to get sections of time series data?
0 Comments
Answers (1)
Steven Lord
on 21 Feb 2019
Turn your datetime array into a duration array by subtracting off the starting time, then use that duration to construct a timetable and index into that timetable using a timerange.
First I'll generate some sample data. T is a datetime array representing some time today.
rng default
secondsPerDay = seconds(days(1));
times = datetime('today');
randomNumberOfSeconds = seconds(randi(secondsPerDay, 10, 1));
T = times + randomNumberOfSeconds
Subtract off the start of today to get a duration and give the timetable some random data. By the way I constructed the example I know I could have just used randomNumberOfSeconds to build the timetable but I'm assuming you don't have the data as a duration already, you just have the datetime array.
tt = timetable(T-times, randi(100, 10, 1))
Let's get all the data from 9 AM to 5 PM (hours 9 through 17 of the day.)
nineToFive = timerange(hours(9), hours(17));
result = tt(nineToFive, :)
Since the first command I used set the random number generator to its default state your tt should be the same as mine. You should see that result has two rows and looking at the original tt you'll see that those are the only two times in the desired range.
0 Comments
See Also
Categories
Find more on Descriptive Statistics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!