I have data as follows (either numerical or logical, it doesn't matter in this case): [0 1 0 1 1 0 1 1 1 0 1 1 1 1 0] Every 0 represents one or more zeroes. I want to detect where consecutive sequences of ones are, but no longer than three after one another. I can do this imperatively with some for- or while-loop, walking over a window of five (?) elements, but I think that's computationally ineffective. How can I do this without loops, but with something like conv or movmean? The expected (logical) result for trains of nonzero values up to three long is [0 1 0 1 1 0 1 1 1 0 0 0 0 0 0] I know I can detect single peaks with: function tf = findsinglenonzeros(x) c = conv(double(x), [1, 1, 1], 'same'); tf = c & x == c; end But now for of nonzero values up to three (or n) long.
Kshitij Singh answered .
2025-11-20
n=3; P=find(~[0 x(:).' 0]); d=diff(P)-1; idx=(d>=1)&(d<=n); locations=P( idx ); lengths=d(idx); z=zeros(1,numel(x)+1); z(locations)=1; z(locations+lengths)=-1; result =cumsum(z(1:end-1)),