MATLAB: How to sum the first 3 values after each zero

cumsumfirst 3 valuessum specific values

Hi all, I have matrix X, and want to sum the first 3 values after each zero. So far I've managed to sum each block of values after a zero, but I need to modify this to output only the first 3 values after a zero.
clear all
clc
x=[0 0 1 2 4 2 5 1 0 0 3 7 9 6 9 0 0 0 0 3 7 0 0 0 2];
t = [0,x,0];
c = cumsum(t);
f = find(diff(t~=0)~=0);
r = c(f(2:2:end))-c(f(1:2:end));
%output is r = [15,34,10,2];
%but i want r = [7, 19, 10, 2];
Thanks guys!

Best Answer

This
x = [0 0 1 2 4 2 5 1 0 0 3 7 9 6 9 0 0 0 0 3 7 0 0 0 2];
dx = [ 0, diff( x ) ];
len = length( x );
is0 = [ false, ( x == 0 ) ];
is0(end) = [];
ix_start = find( is0 & not(dx==0) );
out = nan( size( ix_start ) );
for jj = 1 : length( ix_start )
out(jj) = sum( x( ix_start(jj) : min( ix_start(jj)+2, len ) ) );
end
outputs
>> disp( out )
7 19 10 2