Does anyone know of a function that will take timeseries data and find 12-hour averages throughout (day and night averages)?

3 views (last 30 days)
I have a 17 day timeseries and I would like to calculate 12-hour averages for the data so that I end up with daytime averages and nighttime averages. In this case "day" will be approx 06:00 to 18:00 (12 hours) and night is 18:00 to 06:00 (12 hours). I'm not sure if a function already exists to do this given timestamps and the data vector in question. If not would I want to loop through each 12 hour period? The night data might be problematic since it spans 2 dates. Anyway, I'm thrilled to hear any ideas/advice. I've attached my timestamps (MX) and example data (PH). Timestamps are in matlab time (serial date number from July 23, 2017 to August 9, 2017). Thank you!

Accepted Answer

Walter Roberson
Walter Roberson on 29 Sep 2020
Convert the timeseries to a timetable object, TT, and use
rt = TT.Properties.RowTimes;
first_day = dateshift(rt(1), 'start, 'day');
first_period = first_day + hours(6);
if first_period > rt(1)
first_period = first_period - hours(12);
elseif first_period + hours(12) < rt(1)
first_period = first_period + hours(12);
end
last_day = dateshift(rt(end), 'start', 'day');
last_period = last_day + hours(6);
if last_period + hours(12) < rt(end)
last_period = last_day + hours(30);
elseif last_period < rt(end)
last_period = last_period + hours(12);
end
last_period_start = last_period - hours(12);
periods = first_period : hours(12) : last_period_start;
TT2 = retime(TT, periods 'mean');
Here I do not assume that the data is well-behaved with respect to the timeslots. Instead, I prepare for the possibility that there is partial data before 6am the first day, or after 6pm the last day. I also narrow down in case you can start in the evening on the first day, or end in the morning on the last day. If these factors are never the case, then the calculations of the start and end can potentially be simplified.
,,, There is probably a better way of figuring out the starts and ends, but this is what comes to mind at the moment.
  2 Comments
Heidi Hirsh
Heidi Hirsh on 11 Oct 2020
Edited: Heidi Hirsh on 11 Oct 2020
Is there a straightforward way to adapt what you did to test other intervals for averaging? Say 4hour intervals with the same start time (6am). So averaging over the following intervals:
06:00-10:00
10:00-14:00
14:00-18:00
18:00-22:00
22:00-02:00
02:00-06:00
I thought it might be as simple as replacing 12 with 4 (or my desired interval for averaging) in your code above. I'm wondering if I will run into problems with the ends of the data when it isn't well-behaved with respect to the timeslots.
Thanks!

Sign in to comment.

More Answers (0)

Categories

Find more on Time Series 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!