MATLAB: Sum of nonzero vector elements

elementsindexnonzerosumvector

Hallo everybody!
i have a vector with zeros and nonzero-entries. Now i would like to make the sum of the nonzero-elements between the zeros.example:
v= 1 2 3 0 0 0 4 5 0 6 7 0 8 9
out=6 9 13 17
in addition i would like to know the number of elements in each sum and the index of the first-sum element.
num= 3 2 2 2
indx= 1 7 10 13
can anyone help? thanks

Best Answer

v= [1 2 3 0 0 0 4 5 0 6 7 0 8 9]
ii=[0 v~=0 0]
idx1=strfind(ii,[0 1])
idx2=strfind(ii,[1 0])-1
out=cell2mat(arrayfun(@(x,y) [sum(v(x:y));y-x+1;x],idx1,idx2,'un',0))