MATLAB: How to convert three dimension daily data into monthly mean

daily to monthly

I have three dimension daily data contaning (station, year, day)(387x2x365), i need to convert into monthly mean for each year (387x2x12).
current code is attached below, thank you.
load('prec_aphrodite.mat')
prec=prec_aphrodite;
for i=1:2
for ii=1:387
days=[31 28 31 30 31 30 31 31 30 31 30 31]
dd=0;
for mm=1:12
mmprec=prec((dd+1):days(mm)),3);
for ddd=1:days(mm)
prec_aph_mm(ii,i,mm)=nanmean(prec(((dd+1):dd+days(mm)),3))
dd=dd+days(mm)
end
end
end

Best Answer

Let me try it step-by-step:
% Load the data
load('prec_aphrodite.mat');
% Reshape the data to 730(day)-by-387(site) array
data_year1 = squeeze(prec_aphrodite(:,1,:))';
data_year2 = squeeze(prec_aphrodite(:,2,:))';
Data = [data_year1; data_year2];
% Assuming the first day is 2001/1/1
Time = datetime(2001,1,1):days(1):datetime(2002,12,31);
Time = Time';
% Create timetable by combining 'Time' and 'Data'
TT = table2timetable([table(Time),array2table(Data)]);
% Calculate monthly mean value for each site
TT2 = retime(TT,'monthly','mean');
The result is:
>> TT2
ans =
24×387 timetable
Time Data1 Data2 ...
__________ _______ _______
2001/01/01 0.93232 1.0593 ...
2001/02/01 2.3482 2.4687 ...
2001/03/01 2.3196 2.1202 ...
2001/04/01 0.75275 0.63212 ...
... ... ...