MATLAB: How to sum specific values from a loop and create a new vector

for loopsumvector

If I have this matrix M:
a=1:1:20;
b=[0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 2 0 0];
M=[a,b];
How could I find the i values where M(:,b)>0 (where the second column "b">0), and then take the values of the same row but the first column "a" M(a,:) and make a summation from that row i and i-2, i,e, [i + (i-1)+(i-2)].. like this:
X=[(5+6+7) (12+13+14) (18+17+16)] = [18 39 51]
Besides a vector Y which contains the summation from i-5 until i-3 like this:
Y=[(2+3+4) (9+10+11) (13+14+15)] = [9 30 42]
Both of them for all i values in a vector b of a matrix.

Best Answer

Use bsxfun and sum:
a=1:1:20;
b=[0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 2 0 0];
M=[a(:),b(:)];
idx = find(M(:,2) > 0);
X = sum(bsxfun(@plus, idx, -2:0),2)
Y = sum(bsxfun(@plus, idx, -5:-3),2)
X =
18
39
51
Y =
9
30
42