Sum Numbers Excluding Zeros
Mostrar comentarios más antiguos
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
Respuesta aceptada
Más respuestas (1)
Stephen23
el 12 de Abr. de 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 comentarios
Jon
el 13 de Abr. de 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
el 13 de Abr. de 2019
+1 for both the solutions, Jonathan I highly appreciate your effort too, the solution proposed by you was innovative.
Daniel Boateng
el 14 de Abr. de 2019
Categorías
Más información sobre Number Theory en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!