MATLAB: I want to sum specific elements in an a 2D matrix

loopmatrix

I have a matrix like this
4 3 6 8 1 10 5 2 9
1 10 3 9 4 2 5 7 6
9 5 1 7 8 10 3 4 2
What i want to do is a 3×3 matrix that contains this
For cell (1,1) — (4 + 8 + 5) – 4 (i.e. 4(the first element in the array) + 8(the fourth element in the array) + 5(the 7th element in the array) – 4(my initial cell))
For cell (1,2) — (3 + 1 + 2) – 3 (i.e. 3(the second element in the array) + 1(the fifth element in the array) + 2(the 8th element in the array) – 3(my initial cell))
and so on… For cell (2,1) — (1 + 9 + 5) – 1
It's like calculating the total of all the numbers where the indices are separated by 3
output =
13 3 19
14 11 8
10 12 12

Best Answer

A loop is the only way I can see to do this:
M = [4 3 6 8 1 10 5 2 9
1 10 3 9 4 2 5 7 6
9 5 1 7 8 10 3 4 2];
for k1 = 1:3
for k2 = 1:3
S(k1,k2) = sum(M(k1,3+k2:3:end),2);
end
end
S
S =
13 3 19
14 11 8
10 12 12