Sum Numbers Excluding Zeros
显示 更早的评论
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
采纳的回答
更多回答(1 个)
Stephen23
2019-4-12
>> 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 个评论
Jon
2019-4-13
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
2019-4-13
+1 for both the solutions, Jonathan I highly appreciate your effort too, the solution proposed by you was innovative.
Daniel Boateng
2019-4-14
类别
在 帮助中心 和 File Exchange 中查找有关 Number Theory 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!