MATLAB: Hi Guys! I want to compute annual means of returns based on monthly returns. So I have 363 monthly returns vector and want to compute the following sequence mean(1:12), mean(13:24), mean(25:36)….and so on.

loopsMATLAB

I created the loop but it returns a mistake for which I can't find a solution.
MSCI = BB(1:363,4);
BOND = BB(1:363,5);
c = 12;
path = (1:c:(length(MSCI)));
for i = path
MSCI1(31) = mean(MSCI(i:i+(c-1)));
Bond1(31) = mean(BOND(i:i+(c-1)));
end
What is wrong in this code? Thank you very much in advance

Best Answer

You seem to assume, that something is wrong with your code. Then please mention, why you think so. This is better than letting the readers guess it.
  • I assume, you do not want to store the output to MSCI1(31), but than MSCI1 should be a vector containing all results.
  • The last element of your loop counter i is 361. Then you cannot access MSCI(i+c+1), because this is out of bounds.
MSCI = BB(1:363,4);
BOND = BB(1:363,5);
c = 12;
index = 1:c:(length(MSCI));
for k = 1:length(index) - 1
v = index(k);
MSCI1(k) = mean(MSCI(v:v+c-1));
Bond1(k) = mean(BOND(v:v+c-1));
end
A cheaper solution without a loop:
c = 12;
n = 363 - mod(363, c);
MSCI = reshape(BB(1:n, 4), 12, []);
BOND = reshape(BB(1:n, 5), 12, []);
MSCI1 = mean(MSCI, 1);
Bond1 = mean(BOND, 1);
By the way, path is an important Matlab function. Shadowing it by using its name for a variable can cause serious troubles.