How to sum spesific numbers in an array?

3 visualizzazioni (ultimi 30 giorni)
Rikke
Rikke il 15 Apr 2019
Commentato: Rikke il 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];

Risposta accettata

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

Più risposte (0)

Categorie

Scopri di più su Multidimensional Arrays in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by