Sum Numbers Excluding Zeros
Afficher commentaires plus anciens
I have an array like this [2 2 3 4 0 0 0 0 7 8 2 2]. Please i want to add the numbers excluding the zeros to have something like this[11 0 0 0 0 19] Please is there a way I can do it. Thanks
Réponse acceptée
Plus de réponses (1)
Stephen23
le 12 Avr 2019
>> x = [0,0,0,1,0,2,2,3,4,0,0,0,0,7,8,2,2,0,3,0];
>> y = cumsum(x==0 | [true,x(1:end-1)==0]);
>> z = accumarray(y(:),x(:))
z =
0
0
0
1
0
11
0
0
0
0
19
0
3
0
3 commentaires
Jon
le 13 Avr 2019
Very neat! I knew there must be some very elegant way to do this and you certainly have shown one here. Thank you for introducing me to the accumarray function, I had never encountered that but reading the documentation I can see it can do this (what you have) and much more, especially with the optional function argument.
madhan ravi
le 13 Avr 2019
+1 for both the solutions, Jonathan I highly appreciate your effort too, the solution proposed by you was innovative.
Daniel Boateng
le 14 Avr 2019
Catégories
En savoir plus sur Number Theory dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!