How to sum spesific numbers in an array?

3 Ansichten (letzte 30 Tage)
Rikke
Rikke am 15 Apr. 2019
Kommentiert: Rikke am 15 Apr. 2019
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];

Akzeptierte Antwort

madhan ravi
madhan ravi am 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

Weitere Antworten (0)

Kategorien

Mehr zu Multidimensional Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by