How to sum spesific numbers in an array?

1 view (last 30 days)
Array like this:
A=[1 2 1 1 0 2 2 0 0 2 1 0 2 1 1 0 0];
How to sum every number between each zero occurence like this:
B=[5 0 4 0 0 3 0 4 0 0];
And I also want to remove the zeros from B so I will end up with:
C=[5 4 3 4 ];
Another question also, could I count the number of zeros into another array like this:
D=[1 2 1 2];

Accepted Answer

madhan ravi
madhan ravi on 15 Apr 2019
A=[1 2 1 1 0 2 2 0 0 2 1 0 2 1 1 0 0];
y = cumsum(A==0 | [true,A(1:end-1)==0]);
B = accumarray(y(:),A(:)).'
C=nonzeros(B).'
x=A==0;
Start = strfind([0,x],[0 1]);
End = strfind([x,0],[1 0]);
D= End - Start + 1

More Answers (0)

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!