How to sum spesific numbers in an array?

3 次查看(过去 30 天)
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];

采纳的回答

madhan ravi
madhan ravi 2019-4-15
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by