MATLAB: How to average data to montly data

averagedata averagingdatetimetime averaging

Hello,
I have datetime matrix T (size 1×1037) from 1992 to 2020 at this format :
'1995-11-11 10:06:20'
'1995-11-21 08:04:52'
'1995-12-01 06:03:23'
'1995-12-11 04:01:54'
'1995-12-21 02:00:25'
'1995-12-30 23:58:56'
'1996-01-09 21:57:26'
'1996-01-19 19:55:58'
'1996-01-29 17:54:31'
.
.
.
and another matrix B with the same size 1×1037, which correpondence indices' of time is measurement.
I would like to average this data to montly data and measurements should also be averaged to that specific month.
I tried with for loop but correspondences are mixed.
How can i do this averaging to montly? I would be very pleased for help.

Best Answer

Hi Ahmet,
From your question I understand that you want to club your matrices into one and then run the mean on it to get the monthly average. You can simply create a table from the two matrices and use the groupsummary function on that table in MATLAB to group the data on the basis of months and get the mean.
I have tried implementing the same on the given data. I have a datetime array "st" and have created an array "measure" containing same number of values as in st.
%% st =
% {'1995-11-11 10:06:20';
% '1995-11-21 08:04:52';
% '1995-12-01 06:03:23';
% '1995-12-11 04:01:54';
% '1995-12-21 02:00:25';
% '1995-12-30 23:58:56';
% '1996-01-09 21:57:26';
% '1996-01-19 19:55:58';
% '1996-01-29 17:54:31';
% '1996-11-11 10:06:20'}
measure = [1; 2; 3; 4; 5; 6; 7; 8; 9; 1]
t = datetime(st,'InputFormat','yyyy-MM-dd HH:mm:ss')
data = table(t, measure)
groupsummary(data, 't', 'month', 'mean', 'measure')
This returns the result as:
month_t GroupCount mean_vec1
________ __________ _________
Nov-1995 2 1.5
Dec-1995 4 4.5
Jan-1996 3 8
Nov-1996 1 1
Here I have put the bin as "month" and the function to be applied on measure as "mean".
You can try something on the similar lines with your dataset in groupsummary function.
The groupsummary documentation has all the details about the groupbins. Feel free to leverage the same.
Hope it helps!
Thanks