MATLAB: How to convert time data to be equally spaced

MATLAB

I have a table of data from various times but the times are not all evenly spaced. For instance, there is normally one data point per hour but sometimes there are two or three data points in the same hour. I would like to take the hour time step (1:00 to 2:00, 2:00 to 3:00, etc) and average the data points. Is there a way to do this? 

Best Answer

This can be accomplished using the 'retime' function for timetables. To do this, you will first have to convert the table into a timetable. From there, you can use the 'retime' function with an hourly timestep to take the average. Below is an example of this workflow:
% Generate sample data table
t1 = datetime('01-Jan-2016 00:00:00');
t2 = datetime('01-Jan-2016 6:00:00');
times = (t1:minutes(5):t2)';
temperature = randi([60 100], 1,73)';
weather = table(times, temperature);
% Convert to timetable
weather_time_table = table2timetable(weather);
% Retime using the 'mean' method
hourlymean = retime(weather_time_table, 'hourly', 'mean');
You can compare 'hourlymean' and 'weather_time_table' to see how the data has been aggregated. Note however, that there are many other methods other than 'mean' which can be used when calling 'retime' on a timetable: