How to cumulatively add consecutive ones between zeros in a logical vector
3 次查看(过去 30 天)
显示 更早的评论
I have a vector that looks like
x = [0 0 1 1 0 0 1 1 1 0 0 1]
and am trying to obtain
y = [0 0 1 2 0 0 1 2 3 0 0 1]
without using a loop. Any help would be much appreciated. The answer by Roger Stafford in https://www.mathworks.com/matlabcentral/answers/118828-how-to-count-the-number-of-consecutive-numbers-of-the-same-value-in-an-array is along the lines of what I am trying to achieve, but I am currently unable to manipulate his code to serve my purpose.
0 个评论
采纳的回答
Andrei Bobrov
2017-10-26
y = x(:)';
ii = accumarray(bwlabel(y(:))+1,1);
y = [y,0];
y(strfind(y,[1 0])+1) = -ii(2:end);
out = cumsum(y(1:end-1));
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!