MATLAB: How to calculating monthly average

average

hi all I just want to be sure about this small monthly averaging code
I=1;
for i=1: length(x)/30;
y(i)=mean(x(I:I+29));
L(i)=min(x(I:I+29));
U(i)=max(x(I:I+29));
I=I+29;
end
where x is data matrix (365 day)
thank you

Best Answer

Try this:
dailyValues = rand(1,365); % Sample data
daysInMonths = [31,28,31,30,31,30,31,31,30,31,30,31]
monthEnds = [0, cumsum(daysInMonths)]
for m = 1 : length(monthEnds)-1
firstDay = monthEnds(m)+1;
lastDay = monthEnds(m+1);
fprintf('For month #%d, the first day = %d and the last day = %d\n',...
m, firstDay, lastDay);
monthlyAverage(m) = mean(dailyValues(firstDay:lastDay));
end
% Echo to command window.
monthlyAverage
Of course you need to take leap years into account, which I didn't do.