MATLAB: For loop to find yearly averages

for loop

Hi,
I have runoff data (27,23,360) where the 3rd dimension represents 'months'. I want to find the average runoff for each year. I used the following code to find the average runoff for the first year: a = mean(RUNOFF(:,:,[1:12]),3);
Now I want to use a for loop to show the average runoff for each year so that the output will look like this (27,23,30). I have never used a for loop before so I could use some advice.
Thank you, ruben

Best Answer

You do not need a loop:
s = size(RUNOFF);
RunOffP = reshape(RUNOFF, s(1), s(2), 12, s(3) / 12);
RunOffAvg = squeeze(mean(RunOffP, 3));
This assumes, that the 3rd dimension of the input is a multiple of 12.
This is nicer and faster than a loop:
s = size(RUNOFF);
RunOffAvg = zeros(s(1), s(2), s(3) / 12); % Pre-allocate!
for k = 1:s(3) / 12
ini = (k - 1) * 12 + 1;
fin = ini + 11;
RunOffAvg(:, :, k) = mean(RUNOFF(:, :, ini:fin), 3);
end