MATLAB: Monthly average from yearly data missing days with dates in a cell

for loopmeantime series

Hi there,
I have gotten myself lost. I was able to achieve what I am about to ask using a lot of code but was wondering if there was a way to automate it. I have a large matrix of 364×8 that contains data point (m) over each day of the year (missing 2 days) over 8 time intervals. I have the dates in a cell in the format 01 January 2016 for example. Is there a way to get the averages for each month, for each time interval, automatically? I have been trying to search for 3 characters (i.e Jan) and averages all rows correspondingly, and so on, but have failed miserably.
Previously, I built smaller matrices over the desired time intervals (each month, by indexing) and averaged that way; then recombined the matrices. But, I will be looking to expand my data over multiple years so automation is ideal. Any help would be appreciated.
Thanks
L

Best Answer

Here I create fake data that follow your descriptions. Then I group the datetime vector by month and year and loop through each month to average all the data for that month for each year. In my example, all data are from 2016 but if your data span >1 year this strategy will not combine months from multiple years.
% Fake data
data = rand(364,8);
dates = datetime('01/01/2016') : datetime('12/29/2016');
% Group by month
months = month(dates);
unqMonths = unique(months);
% Group by year
years = year(dates);
unqYears = unique(years);
% Loop through each month and do averaging
moAvg = zeros(length(unqMonths) * length(unqYears), 1);
for j = 1:length(unqYears)
for i = 1:length(unqMonths)
monthyearIdx = months==unqMonths(i) & years == unqYears(j);
thisMonthData = data(monthyearIdx, :);
moAvg(i) = mean(thisMonthData(:));
end
end