MATLAB: How to get the sum of several sets of nonzeros in array

findnonzero

Hi,
I am working with stepwatch data, and have a long array of combined numbers and zeros. I want to figure out the total number of steps within a walking bout. An example of a part of an array is [0 0 0 0 2 4 1 0 0 1 5 3 0 0 0 0 2 3 0 0 7 2 3 1 2 0 0 0 0].
What I want as output is the sum of each set of nonzeros. So [ 7 9 5 13]
I tried it with the find function, but then I can only find the indices of the first and last zero or nonzero, and not the second, third, fourth etc… Can somebody help me?

Best Answer

Here is one way:
%demo data
v = [0 0 0 0 2 4 1 0 0 1 5 3 0 0 0 0 2 3 0 0 7 2 3 1 2 0 0 0 0];
endruns = find(diff([v~=0, 0]) == -1);
cumidx = zeros(size(v));
cumidx(endruns) = 1;
result = accumarray(cumsum([1; cumidx(1:end-1).']), v)
Note that result will end with a 0 if the last run ends in 0.